IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,549 @@
|
||||
"""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))
|
||||
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()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Exact owned API credit and atomic non-destructive return-to-main contracts."""
|
||||
import ast
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'bot'))
|
||||
import account_balances
|
||||
from account_limits import account_uid, account_token_names
|
||||
|
||||
|
||||
class AccountBalancesTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.bot = str(Path(temp.name) / 'bot.db')
|
||||
self.gw = str(Path(temp.name) / 'api.db')
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
con.executescript("CREATE TABLE users(tg_id INTEGER PRIMARY KEY,token_name TEXT,api_key TEXT,"
|
||||
"banned INTEGER DEFAULT 0,api_blocked INTEGER DEFAULT 0,created INTEGER DEFAULT 0,"
|
||||
"unlim_until INTEGER DEFAULT 0,key_locked INTEGER DEFAULT 0);"
|
||||
"INSERT INTO users(tg_id,token_name,api_key) VALUES(123,'tg123','sk-main-key');"
|
||||
"CREATE TABLE econ_tx(src INTEGER,dst INTEGER,units INTEGER,type TEXT,ts INTEGER);")
|
||||
with closing(sqlite3.connect(self.gw)) as con:
|
||||
con.execute('CREATE TABLE tokens(id INTEGER PRIMARY KEY,name TEXT,key TEXT,status INTEGER DEFAULT 1,'
|
||||
'remain_quota INTEGER DEFAULT 0,used_quota INTEGER DEFAULT 0,unlimited_quota INTEGER DEFAULT 0,'
|
||||
'expired_time INTEGER DEFAULT -1,deleted_at INTEGER,model_limits TEXT DEFAULT "base",'
|
||||
'model_limits_enabled INTEGER DEFAULT 1,"group" TEXT DEFAULT "t1",created_time INTEGER DEFAULT 0)')
|
||||
con.executemany('INSERT INTO tokens(name,key,remain_quota) VALUES(?,?,?)', [
|
||||
('tg123','main-key',1000000),('tg123-k1','extra-key-1',2000000),
|
||||
('tg123-k2','extra-key-2',3000000),('pm123','promo-key',4000000),
|
||||
('sol123','sol-key',5000000),('sol123-k1','sol-extra-key',500000),
|
||||
('tg456','foreign-key',9000000),('tg1234','prefix-key',9000000),
|
||||
('tg123-k1foreign','suffix-key',9000000),('tg123-k01','leading-zero-key',9000000)])
|
||||
con.commit()
|
||||
tree = ast.parse((ROOT/'bot/webapp/mk_daemon.py').read_text(encoding='utf-8'))
|
||||
functions = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))]
|
||||
self.ns = dict(globals(), BOT_DB=self.bot, GW_DB=self.gw, Q=500000,
|
||||
g=SimpleNamespace(MK_CAP={1:4},badge_of=lambda uid:1,KEY_WAIT_SEC=86400))
|
||||
exec(compile(ast.Module(body=functions,type_ignores=[]), 'isolated-key-daemon', 'exec'), self.ns)
|
||||
|
||||
def sql(self, query, params=(), bot=False):
|
||||
with closing(sqlite3.connect(self.bot if bot else self.gw)) as con:
|
||||
result = con.execute(query, params).fetchall()
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
def snapshot(self):
|
||||
with closing(sqlite3.connect(self.gw)) as con:
|
||||
con.row_factory = sqlite3.Row
|
||||
return account_balances.snapshot(con, 123, {'api_key':'sk-main-key'})
|
||||
|
||||
def command(self, action='return_all', request_id='return-all-offline-123'):
|
||||
return self.ns['dispatch'](dict(cmd=action, uid=123,
|
||||
**({} if action == 'list' else {'request_id':request_id})))
|
||||
|
||||
def test_aggregate_counts_every_owned_key_once_excludes_foreign_malformed_deleted(self):
|
||||
self.sql("INSERT INTO tokens(name,key,remain_quota,deleted_at) VALUES('tg123-k9','deleted',9000000,1)")
|
||||
state = self.snapshot()
|
||||
self.assertEqual(state['main_balance_usd'], 12)
|
||||
self.assertEqual(state['extras_balance_usd'], 11)
|
||||
self.assertEqual(state['promo_balance_usd'], 8)
|
||||
self.assertEqual(state['total_balance_usd'], 31)
|
||||
self.assertEqual(state['balance_ambiguous_names'], [])
|
||||
listing = self.command('list')
|
||||
self.assertTrue(listing['ok'], listing)
|
||||
self.assertEqual(listing['total_balance_usd'], 31)
|
||||
|
||||
def test_duplicate_names_and_shared_credentials_never_inflate_the_aggregate(self):
|
||||
self.sql("INSERT INTO tokens(name,key,remain_quota) VALUES('tg123-k1','duplicate-extra',9000000)")
|
||||
state = self.snapshot()
|
||||
self.assertEqual(state['total_balance_usd'], 27)
|
||||
self.assertEqual(state['balance_ambiguous_names'], ['tg123-k1'])
|
||||
self.sql("INSERT INTO tokens(name,key,remain_quota) VALUES('tg456-k9','extra-key-2',9000000)")
|
||||
state = self.snapshot()
|
||||
self.assertEqual(state['total_balance_usd'], 21)
|
||||
self.assertEqual(set(state['balance_ambiguous_names']), {'tg123-k1','tg123-k2'})
|
||||
|
||||
def test_return_all_is_receipted_atomic_and_never_deletes_or_reactivates_credentials(self):
|
||||
before = self.sql('SELECT COUNT(*),SUM(remain_quota) FROM tokens')
|
||||
statuses = self.sql('SELECT id,status,deleted_at FROM tokens ORDER BY id')
|
||||
first = self.command()
|
||||
replay = self.command()
|
||||
self.assertTrue(first['ok'], first)
|
||||
self.assertEqual(first, replay)
|
||||
self.assertEqual(first['moved_usd'], 11)
|
||||
self.assertEqual(self.sql('SELECT COUNT(*),SUM(remain_quota) FROM tokens'), before)
|
||||
self.assertEqual(self.sql('SELECT id,status,deleted_at FROM tokens ORDER BY id'), statuses)
|
||||
self.assertEqual(self.sql("SELECT remain_quota FROM tokens WHERE name='tg123'"), [(6500000,)])
|
||||
self.assertEqual(self.sql("SELECT SUM(remain_quota) FROM tokens WHERE name IN ('tg123-k1','tg123-k2','sol123-k1')"), [(0,)])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM econ_tx', bot=True), [(1,)])
|
||||
self.assertEqual(self.snapshot()['total_balance_usd'], 31)
|
||||
|
||||
def test_return_all_recovers_exhausted_main_and_preserves_multiple_source_totals(self):
|
||||
self.sql("UPDATE tokens SET remain_quota=0,status=4 WHERE name='tg123'")
|
||||
self.sql("UPDATE tokens SET status=4 WHERE name IN ('tg123-k1','tg123-k2','sol123-k1')")
|
||||
before = self.sql('SELECT COUNT(*),SUM(remain_quota) FROM tokens')
|
||||
first = self.command()
|
||||
self.assertTrue(first['ok'], first)
|
||||
self.assertEqual(first['moved_usd'], 11)
|
||||
self.assertEqual(self.sql('SELECT COUNT(*),SUM(remain_quota) FROM tokens'), before)
|
||||
self.assertEqual(self.sql("SELECT remain_quota,status FROM tokens WHERE name='tg123'"),
|
||||
[(5500000, 1)])
|
||||
self.assertEqual(self.sql("SELECT SUM(remain_quota) FROM tokens WHERE name IN ('tg123-k1','tg123-k2','sol123-k1')"),
|
||||
[(0,)])
|
||||
self.assertEqual(self.command(), first)
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM econ_tx', bot=True), [(1,)])
|
||||
|
||||
def test_parallel_retries_move_once_with_one_receipt(self):
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(lambda _: self.command(), range(4)))
|
||||
self.assertTrue(all(item['ok'] for item in results), results)
|
||||
self.assertTrue(all(item == results[0] for item in results))
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM wa_key_operations'), [(1,)])
|
||||
self.assertEqual(self.snapshot()['total_balance_usd'], 31)
|
||||
|
||||
def test_paused_unlimited_and_banned_users_cannot_use_return_to_bypass_policy(self):
|
||||
for field, value in (('status',2),('unlimited_quota',1)):
|
||||
self.sql('UPDATE tokens SET '+field+'=? WHERE name="tg123-k2"', (value,))
|
||||
before = self.sql('SELECT id,remain_quota,status FROM tokens ORDER BY id')
|
||||
result = self.command(request_id='rejected-return-'+field)
|
||||
self.assertFalse(result['ok'])
|
||||
self.assertEqual(self.sql('SELECT id,remain_quota,status FROM tokens ORDER BY id'), before)
|
||||
self.sql('UPDATE tokens SET '+field+'=? WHERE name="tg123-k2"', (1 if field=='status' else 0,))
|
||||
self.sql('UPDATE users SET banned=1 WHERE tg_id=123', bot=True)
|
||||
self.assertFalse(self.command()['ok'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,128 @@
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import account_key_status as aks
|
||||
|
||||
|
||||
UID = 1001
|
||||
|
||||
|
||||
def _bot(path, rows):
|
||||
con = sqlite3.connect(str(path))
|
||||
try:
|
||||
con.execute("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT, api_key TEXT)")
|
||||
con.executemany("INSERT INTO users(tg_id,token_name,api_key) VALUES(?,?,?)", rows)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _gw(path, rows):
|
||||
con = sqlite3.connect(str(path))
|
||||
try:
|
||||
con.execute("CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, key TEXT, "
|
||||
"status INTEGER, deleted_at INTEGER)")
|
||||
con.executemany("INSERT INTO tokens(id,name,key,status,deleted_at) VALUES(?,?,?,?,?)", rows)
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _one(tmp_path, bot_row=(UID, None, None), gw_rows=()):
|
||||
bot = tmp_path / "bot.db"
|
||||
gw = tmp_path / "gw.db"
|
||||
_bot(bot, [bot_row])
|
||||
_gw(gw, gw_rows)
|
||||
return bot, gw
|
||||
|
||||
|
||||
def test_canonical_live_key_is_present_without_binding(tmp_path):
|
||||
bot, gw = _one(tmp_path, gw_rows=[(1, "tg1001", "sk-main", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.MAIN_PRESENT}
|
||||
|
||||
|
||||
def test_confirmed_requires_exact_live_key_and_matching_material(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "tg1001", "sk-main"),
|
||||
gw_rows=[(1, "tg1001", "main", 2, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.MAIN_CONFIRMED}
|
||||
|
||||
|
||||
def test_deleted_or_nonlive_canonical_is_not_a_main(tmp_path):
|
||||
bot, gw = _one(tmp_path, gw_rows=[(1, "tg1001", "sk-main", 3, None),
|
||||
(2, "tg1001", "sk-old", 1, 123)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.NO_MAIN}
|
||||
|
||||
|
||||
def test_secondary_only_is_not_a_confirmed_primary_even_when_bound(tmp_path):
|
||||
bot, gw = _one(tmp_path, gw_rows=[(1, "tg1001-k2", "k2", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.NO_MAIN}
|
||||
|
||||
bound = tmp_path / "bound"
|
||||
bound.mkdir()
|
||||
bot2, gw2 = _one(bound, bot_row=(UID, "tg1001-k2", "sk-k2"),
|
||||
gw_rows=[(1, "tg1001-k2", "k2", 1, None)])
|
||||
assert aks.main_key_states(bot2, gw2, [UID]) == {UID: aks.NO_MAIN}
|
||||
|
||||
|
||||
def test_pm_binding_is_not_a_primary_key(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "pm1001", "sk-pm"),
|
||||
gw_rows=[(1, "pm1001", "pm", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.NO_MAIN}
|
||||
|
||||
|
||||
def test_secondary_pointer_confirms_only_matching_canonical_key(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "tg1001-k2", "sk-main"),
|
||||
gw_rows=[(1, "tg1001", "main", 1, None),
|
||||
(2, "tg1001-k2", "secondary", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.MAIN_CONFIRMED}
|
||||
|
||||
|
||||
def test_duplicate_live_primary_binding_does_not_confirm(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "tg1001", "sk-main"),
|
||||
gw_rows=[(1, "tg1001", "main", 1, None),
|
||||
(2, "tg1001", "main", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.MAIN_PRESENT}
|
||||
|
||||
|
||||
def test_foreign_binding_never_confirms(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "tg2002", "sk-other"),
|
||||
gw_rows=[(1, "tg2002", "other", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.NO_MAIN}
|
||||
|
||||
|
||||
def test_key_mismatch_does_not_confirm_but_canonical_is_present(tmp_path):
|
||||
bot, gw = _one(tmp_path, bot_row=(UID, "tg1001", "sk-wrong"),
|
||||
gw_rows=[(1, "tg1001", "right", 1, None)])
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.MAIN_PRESENT}
|
||||
|
||||
|
||||
def test_missing_database_is_unavailable_not_none(tmp_path):
|
||||
bot = tmp_path / "bot.db"
|
||||
_bot(bot, [(UID, None, None)])
|
||||
missing = tmp_path / "missing.db"
|
||||
assert aks.main_key_states(bot, missing, [UID]) == {UID: aks.UNAVAILABLE}
|
||||
assert not missing.exists()
|
||||
|
||||
|
||||
def test_missing_table_is_unavailable(tmp_path):
|
||||
bot = tmp_path / "bot.db"
|
||||
_bot(bot, [(UID, None, None)])
|
||||
gw = tmp_path / "gw.db"
|
||||
sqlite3.connect(str(gw)).close()
|
||||
assert aks.main_key_states(bot, gw, [UID]) == {UID: aks.UNAVAILABLE}
|
||||
|
||||
|
||||
def test_ten_uid_batch_has_no_secret_in_result(tmp_path):
|
||||
rows = [(uid, None, None) for uid in range(2001, 2011)]
|
||||
gw_rows = [(i, "tg%d" % uid, "secret-%d" % uid, 1, None)
|
||||
for i, uid in enumerate(range(2001, 2011), 1)]
|
||||
bot = tmp_path / "bot.db"
|
||||
gw = tmp_path / "gw.db"
|
||||
_bot(bot, rows)
|
||||
_gw(gw, gw_rows)
|
||||
states = aks.main_key_states(bot, gw, list(range(2001, 2011)))
|
||||
assert states == {uid: aks.MAIN_PRESENT for uid in range(2001, 2011)}
|
||||
assert "secret-" not in repr(states)
|
||||
@@ -0,0 +1,93 @@
|
||||
from contextlib import closing
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
"limits_under_test", Path(__file__).parents[1] / "bot" / "account_limits.py")
|
||||
assert SPEC is not None and SPEC.loader is not None
|
||||
limits = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(limits)
|
||||
|
||||
|
||||
class AccountUsageQueryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.path = Path(self.tmp.name) / "usage.db"
|
||||
with closing(sqlite3.connect(self.path)) as con, con:
|
||||
con.execute("CREATE TABLE logs(type INTEGER,created_at INTEGER,token_name TEXT,quota INTEGER)")
|
||||
con.execute("CREATE INDEX idx_logs_top24 ON logs(type,created_at)")
|
||||
con.executemany("INSERT INTO logs VALUES(?,?,?,?)", [
|
||||
(2, 100, "tg123", 11), (2, 101, "pm123-k2", 13),
|
||||
(2, 199, "sol123-k9", 17), (2, 150, "tg123-k1", None),
|
||||
(2, 99, "tg123", 101), (2, 200, "tg123", 103),
|
||||
(1, 150, "tg123", 107), (None, 150, "tg123", 109),
|
||||
(2, 150, "tg1234", 113), (2, 150, "tg123-k01", 127),
|
||||
(2, 150, "tg123-k1foreign", 131), (2, 150, "pm123-k0", 137),
|
||||
(2, 150, "sol123-k\u0661", 139), (2, 150, "tg0123", 149),
|
||||
])
|
||||
|
||||
def index(self, sql):
|
||||
with closing(sqlite3.connect(self.path)) as con, con:
|
||||
con.execute(sql)
|
||||
|
||||
def test_exact_historical_credentials_time_bounds_and_type_are_preserved(self):
|
||||
# No tokens table: deleted/rotated credentials must still count.
|
||||
self.index("CREATE INDEX idx_logs_token_name ON logs(token_name)")
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41)
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 123, 100), 144)
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 100), 0)
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 456, 100, 200), 0)
|
||||
|
||||
def test_missing_partial_wrong_column_and_expression_index_fall_back(self):
|
||||
indexes = [None,
|
||||
"CREATE INDEX idx_logs_token_name ON logs(token_name) WHERE type=1",
|
||||
"CREATE INDEX idx_logs_token_name ON logs(quota)",
|
||||
"CREATE INDEX idx_logs_token_name ON logs(lower(token_name))"]
|
||||
for sql in indexes:
|
||||
with self.subTest(index=sql):
|
||||
with closing(sqlite3.connect(self.path)) as con, con:
|
||||
con.execute("DROP INDEX IF EXISTS idx_logs_token_name")
|
||||
if sql:
|
||||
con.execute(sql)
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41)
|
||||
|
||||
def test_indexed_usage_does_not_scan_other_accounts_daily_logs(self):
|
||||
self.index("CREATE INDEX idx_logs_token_name ON logs(token_name)")
|
||||
with closing(sqlite3.connect(self.path)) as con, con:
|
||||
con.executemany("INSERT INTO logs VALUES(2,150,?,1)",
|
||||
[("tg%d" % i,) for i in range(10000, 30000)])
|
||||
real_connect = sqlite3.connect
|
||||
callbacks = []
|
||||
|
||||
def connect(*args, **kwargs):
|
||||
con = real_connect(*args, **kwargs)
|
||||
con.set_progress_handler(lambda: callbacks.append(1) or 0, 100)
|
||||
return con
|
||||
|
||||
with patch.object(limits.sqlite3, "connect", side_effect=connect):
|
||||
self.assertEqual(limits.daily_spent_units(self.path, 123, 100, 200), 41)
|
||||
# SQLite instruction budget, not a load-sensitive wall-clock deadline.
|
||||
self.assertLess(len(callbacks), 100)
|
||||
|
||||
def test_invalid_intervals_and_missing_database_fail_closed(self):
|
||||
for start, end in [(100, 99), (True, 200), (100, 200.0)]:
|
||||
with self.subTest(start=start, end=end), self.assertRaises(ValueError):
|
||||
limits.daily_spent_units(self.path, 123, start, end)
|
||||
missing = Path(self.tmp.name) / "missing.db"
|
||||
with self.assertRaises(sqlite3.DatabaseError):
|
||||
limits.daily_spent_units(missing, 123, 100, 200)
|
||||
self.assertFalse(missing.exists())
|
||||
with closing(sqlite3.connect(self.path)) as con, con:
|
||||
con.execute("ALTER TABLE logs RENAME COLUMN quota TO missing_quota")
|
||||
with self.assertRaises(sqlite3.DatabaseError):
|
||||
limits.daily_spent_units(self.path, 123, 100, 200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,238 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,336 @@
|
||||
// Receipt-driven UX for the coding assistant in the Mini App.
|
||||
// The regression: a provider error arriving with a *terminal* receipt used to be routed
|
||||
// through agentStop(), which posted agent_cancel to a finished operation and rendered
|
||||
// «Операция уже завершилась. Уже выполненные действия не отменяются.» — a false claim about
|
||||
// a request that never ran. The driver now trusts the receipt: failed/cancelled are errors,
|
||||
// and the draft is restored only when uncertain===false && side_effect_started===false.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const html = new URL(process.env.IISHKO_UI_HTML || '../bot/webapp/static/index.html', import.meta.url);
|
||||
const source = readFileSync(html, 'utf8');
|
||||
|
||||
function scriptBlocks(text) {
|
||||
const blocks = [];
|
||||
const pattern = /<script\b[^>]*>([\s\S]*?)<\/script>/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(text))) blocks.push(match[1]);
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function between(text, start, end) {
|
||||
const from = text.indexOf(start);
|
||||
assert.ok(from >= 0, 'missing anchor: ' + start);
|
||||
const to = text.indexOf(end, from + start.length);
|
||||
assert.ok(to >= 0, 'missing end anchor: ' + end);
|
||||
return text.slice(from, to);
|
||||
}
|
||||
|
||||
const helpers = scriptBlocks(source).find((block) => block.includes('const MiniAppFlows='));
|
||||
assert.ok(helpers, 'the MiniAppFlows helper script must exist');
|
||||
|
||||
const helperContext = vm.createContext({
|
||||
window: {},
|
||||
document: {getElementById: () => null},
|
||||
crypto: globalThis.crypto,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
console,
|
||||
});
|
||||
vm.runInContext(helpers, helperContext, {filename: 'miniapp-flow-helpers.js'});
|
||||
const MiniAppFlows = vm.runInContext('MiniAppFlows', helperContext);
|
||||
|
||||
const region = between(source, 'function agentFailureText(error){', '/* ---------- напоминания');
|
||||
assert.ok(region.includes('async function agentSend('), 'agentSend must live inside the extracted region');
|
||||
assert.ok(region.includes('function agentStop('), 'agentStop must live inside the extracted region');
|
||||
|
||||
function makeHarness() {
|
||||
const state = {
|
||||
posted: [],
|
||||
texts: [],
|
||||
restores: 0,
|
||||
busy: [],
|
||||
notice: '',
|
||||
released: 0,
|
||||
chatReceipt: () => null,
|
||||
cancelReply: {ok: true, state: 'completed', uncertain: false, side_effect_started: true},
|
||||
};
|
||||
const operation = {id: '', stopping: false, cancelPromise: null, epoch: 0, uid: 'u1'};
|
||||
const capture = (...args) => {
|
||||
state.texts.push(args.map((value) => {
|
||||
if (typeof value === 'string') return value;
|
||||
try { return JSON.stringify(value); } catch { return String(value); }
|
||||
}).join(' | '));
|
||||
};
|
||||
const draftSnapshot = {text: 'привет', revision: 0};
|
||||
const draft = {
|
||||
snapshot: () => draftSnapshot,
|
||||
consume: () => 0,
|
||||
restore: () => { state.restores += 1; return true; },
|
||||
read: () => 'привет',
|
||||
write() {},
|
||||
clear() {},
|
||||
};
|
||||
const context = [
|
||||
{role: 'user', content: 'привет'},
|
||||
];
|
||||
context.messages = context;
|
||||
const scope = {
|
||||
MiniAppFlows,
|
||||
document: {getElementById: () => null, addEventListener() {}, createElement: () => ({style: {}})},
|
||||
$: (selector) => (selector === '#ain'
|
||||
? {value: 'привет', style: {}, focus() {}, disabled: false, scrollHeight: 0}
|
||||
: null),
|
||||
TIMEOUTS: {agent_chat: 1000},
|
||||
post: async (action, body) => {
|
||||
state.posted.push({action, body});
|
||||
if (action === 'agent_chat') {
|
||||
const receipt = state.chatReceipt(body) || null;
|
||||
if (receipt) {
|
||||
const error = new Error(receipt.message || 'request failed');
|
||||
error.status = receipt.status || 503;
|
||||
error.data = Object.assign({}, receipt, {
|
||||
operation_id: receipt.operation_id === undefined ? body?.operation_id : receipt.operation_id,
|
||||
});
|
||||
delete error.data.status;
|
||||
throw error;
|
||||
}
|
||||
return {ok: true, operation_id: body?.operation_id};
|
||||
}
|
||||
// The real endpoint always echoes operation_id; agentStop validates it.
|
||||
if (action === 'agent_cancel') return Object.assign({operation_id: body?.operation_id}, state.cancelReply);
|
||||
return {ok: true};
|
||||
},
|
||||
agentOperations: {
|
||||
current: () => (operation.id ? operation : null),
|
||||
begin: (id) => {
|
||||
operation.id = typeof id === 'string' && id ? id : 'op-generated';
|
||||
operation.stopping = false;
|
||||
operation.cancelError = '';
|
||||
// Same epoch/uid the real begin() stamps; otherwise every guard drops the receipt.
|
||||
operation.epoch = scope.agentEpoch;
|
||||
operation.uid = scope.resolvedUid;
|
||||
return operation;
|
||||
},
|
||||
start: (id) => scope.agentOperations.begin(id),
|
||||
new: (id) => scope.agentOperations.begin(id),
|
||||
owns: () => true,
|
||||
release: () => { state.released += 1; },
|
||||
},
|
||||
agentDraft: draft,
|
||||
createRamDraft: () => draft,
|
||||
restoreAgentDraft: () => { state.restores += 1; return true; },
|
||||
rememberAgentDraft: () => {},
|
||||
agentMsgs: [],
|
||||
agentBubble: capture,
|
||||
logAppend: capture,
|
||||
popup: capture,
|
||||
alert: capture,
|
||||
agentOperationNotice: (text) => { state.notice = String(text ?? ''); capture(text); },
|
||||
agentTypingStart: () => {},
|
||||
agentTypingStop: () => {},
|
||||
agentTypingHtml: () => '',
|
||||
agentScroll: () => {},
|
||||
haptic: () => {},
|
||||
agSetBusy: (value) => state.busy.push(value),
|
||||
agSave: () => {},
|
||||
agContext: () => context,
|
||||
updateAgentFile: () => {},
|
||||
updateAgentModelControl: () => {},
|
||||
loadAgentModels: async () => {},
|
||||
agentFile: null,
|
||||
agentFileEpoch: 0,
|
||||
agentModel: 'test-model',
|
||||
agentModels: ['test-model'],
|
||||
agentBusy: false,
|
||||
agentComposing: false,
|
||||
agentClearPending: false,
|
||||
agentEpoch: 0,
|
||||
agentLastPrompt: '',
|
||||
agentLastActual: '',
|
||||
agentVmSeen: false,
|
||||
agentSandboxOn: true,
|
||||
agentRetry: null,
|
||||
resolvedUid: 'u1',
|
||||
escapeHtml: (value) => String(value ?? ''),
|
||||
esc: (value) => String(value ?? ''),
|
||||
isExactModelId: (id) => typeof id === 'string' && id.length > 0,
|
||||
opaquePattern: /^[A-Za-z0-9_.:-]{4,80}$/,
|
||||
retryAfterText: () => '',
|
||||
fetch: async () => ({ok: false, status: 500, json: async () => ({})}),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
requestAnimationFrame: (fn) => setTimeout(fn, 0),
|
||||
};
|
||||
const proxy = new Proxy(scope, {
|
||||
has: () => true,
|
||||
get: (target, key) => {
|
||||
if (key === Symbol.unscopables) return undefined;
|
||||
if (key in target) return target[key];
|
||||
if (typeof key === 'string' && key in globalThis) return globalThis[key];
|
||||
return undefined;
|
||||
},
|
||||
set: (target, key, value) => { target[key] = value; return true; },
|
||||
});
|
||||
const factory = new Function('__scope__', `with(__scope__){\n${region}\nreturn {agentSend:agentSend,agentStop:agentStop};\n}`);
|
||||
return {driver: factory(proxy), state, operation, draft};
|
||||
}
|
||||
|
||||
function chatPostCount(state) {
|
||||
return state.posted.filter((entry) => entry.action === 'agent_chat').length;
|
||||
}
|
||||
|
||||
function cancelPostCount(state) {
|
||||
return state.posted.filter((entry) => entry.action === 'agent_cancel').length;
|
||||
}
|
||||
|
||||
test('receipt helpers treat a missing side_effect_started flag as unknown, never as "nothing ran"', () => {
|
||||
assert.deepEqual({...MiniAppFlows.agentReceiptView(null)}, {state: '', uncertain: true, side_effect_started: null});
|
||||
assert.equal(MiniAppFlows.agentReceiptView({state: 'failed', uncertain: false}).side_effect_started, null);
|
||||
assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'failed'}}, 'op-b'), null);
|
||||
assert.equal(MiniAppFlows.agentFailureReceipt({data: {state: 'failed'}}, 'op-a'), null);
|
||||
assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'completed'}}, 'op-a'), null);
|
||||
assert.equal(MiniAppFlows.agentFailureReceipt({data: {operation_id: 'op-a', state: 'failed'}}, 'op-a').state, 'failed');
|
||||
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false}), false);
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false, side_effect_started: true}), false);
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: true, side_effect_started: false}), false);
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore({state: 'completed', uncertain: false, side_effect_started: false}), false);
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore({state: 'failed', uncertain: false, side_effect_started: false}), true);
|
||||
// [CANCEL-COMPAT] failed:true beats the legacy state string.
|
||||
const legacy = MiniAppFlows.agentReceiptView({state: 'completed', failed: true, uncertain: false, side_effect_started: false});
|
||||
assert.equal(legacy.state, 'failed');
|
||||
assert.equal(MiniAppFlows.agentSafeToRestore(legacy), true);
|
||||
|
||||
const refused = MiniAppFlows.agentTerminalNote('failed', {state: 'failed', uncertain: false, side_effect_started: false});
|
||||
assert.match(refused, /Запрос не выполнен/);
|
||||
assert.match(refused, /Внешние действия не запускались/);
|
||||
const unknown = MiniAppFlows.agentTerminalNote('failed', {state: 'failed', uncertain: true, side_effect_started: true});
|
||||
assert.match(unknown, /неизвестен/);
|
||||
const completed = MiniAppFlows.agentTerminalNote('completed', {state: 'completed', uncertain: false, side_effect_started: true});
|
||||
assert.match(completed, /Операция уже завершилась/);
|
||||
assert.match(completed, /уже запускались/);
|
||||
});
|
||||
|
||||
test('a terminal failed receipt before any tool restores the draft without posting agent_cancel', async () => {
|
||||
const {driver, state} = makeHarness();
|
||||
state.chatReceipt = () => ({
|
||||
status: 403,
|
||||
state: 'failed',
|
||||
uncertain: false,
|
||||
side_effect_started: false,
|
||||
message: 'Сначала создай активный API-ключ во вкладке «Ключи».',
|
||||
});
|
||||
|
||||
await driver.agentSend();
|
||||
|
||||
assert.equal(chatPostCount(state), 1);
|
||||
assert.equal(cancelPostCount(state), 0, 'a definitive terminal failure must not be replayed as a cancel');
|
||||
assert.equal(state.restores, 1, 'the draft must be restored exactly once');
|
||||
const text = state.texts.join('\n');
|
||||
assert.match(text, /Запрос не выполнен/);
|
||||
assert.match(text, /Внешние действия не запускались/);
|
||||
assert.match(text, /Черновик сохранён/);
|
||||
assert.doesNotMatch(text, /Уже выполненные действия не отменяются/);
|
||||
assert.ok(state.busy.includes(false), 'the send button must be released');
|
||||
});
|
||||
|
||||
test('a failed receipt after side effects keeps the draft and says the outcome is unknown', async () => {
|
||||
const {driver, state} = makeHarness();
|
||||
state.chatReceipt = () => ({
|
||||
status: 503,
|
||||
state: 'failed',
|
||||
uncertain: true,
|
||||
side_effect_started: true,
|
||||
message: 'Модель сейчас не ответила.',
|
||||
});
|
||||
|
||||
await driver.agentSend();
|
||||
|
||||
assert.equal(cancelPostCount(state), 0);
|
||||
assert.equal(state.restores, 0, 'a draft must not be restored when external actions already ran');
|
||||
const text = state.texts.join('\n');
|
||||
assert.match(text, /неизвестен/);
|
||||
assert.doesNotMatch(text, /Черновик сохранён/);
|
||||
assert.doesNotMatch(text, /Уже выполненные действия не отменяются/);
|
||||
});
|
||||
|
||||
test('an error without a matching receipt stays conservative and asks the server to stop', async () => {
|
||||
const {driver, state} = makeHarness();
|
||||
state.chatReceipt = () => ({
|
||||
status: 500,
|
||||
state: 'failed',
|
||||
uncertain: true,
|
||||
side_effect_started: true,
|
||||
operation_id: 'some-other-operation',
|
||||
message: 'Внутренняя ошибка.',
|
||||
});
|
||||
// [CANCEL-COMPAT] the server answers a failed finished record with state='completed'
|
||||
// plus failed:true; the UI must explain the failure, never imply a clean finish.
|
||||
state.cancelReply = {ok: true, state: 'completed', failed: true, uncertain: true, side_effect_started: true};
|
||||
|
||||
await driver.agentSend();
|
||||
|
||||
assert.equal(cancelPostCount(state), 1, 'an unverifiable error must still try to stop the operation');
|
||||
assert.equal(state.restores, 0);
|
||||
const text = state.texts.join('\n');
|
||||
assert.match(text, /Запрос не выполнен/);
|
||||
assert.match(text, /неизвестен/);
|
||||
assert.doesNotMatch(text, /Операция уже завершилась/);
|
||||
});
|
||||
|
||||
test('agentStop reports a failed operation as a failure, not as success', async () => {
|
||||
const {driver, state, operation} = makeHarness();
|
||||
operation.id = 'op-failed';
|
||||
state.cancelReply = {ok: true, operation_id: 'op-failed', state: 'completed', failed: true, uncertain: false, side_effect_started: false};
|
||||
|
||||
await driver.agentStop();
|
||||
|
||||
assert.equal(cancelPostCount(state), 1);
|
||||
const text = state.texts.join('\n');
|
||||
assert.match(text, /Запрос не выполнен/);
|
||||
assert.match(text, /Внешние действия не запускались/);
|
||||
assert.doesNotMatch(text, /Операция уже завершилась/);
|
||||
|
||||
// Forward-compatible: a server that can emit state='failed' directly is honoured too.
|
||||
const direct = makeHarness();
|
||||
direct.operation.id = 'op-failed-direct';
|
||||
direct.state.cancelReply = {ok: true, operation_id: 'op-failed-direct', state: 'failed', uncertain: false, side_effect_started: false};
|
||||
await direct.driver.agentStop();
|
||||
assert.match(direct.state.texts.join('\n'), /Запрос не выполнен/);
|
||||
});
|
||||
|
||||
test('agentStop keeps the truthful note for completed and cancelled receipts', async () => {
|
||||
const completed = makeHarness();
|
||||
completed.operation.id = 'op-completed';
|
||||
completed.state.cancelReply = {ok: true, operation_id: 'op-completed', state: 'completed', uncertain: false, side_effect_started: true};
|
||||
await completed.driver.agentStop();
|
||||
const completedText = completed.state.texts.join('\n');
|
||||
assert.match(completedText, /Операция уже завершилась/);
|
||||
assert.match(completedText, /уже запускались/);
|
||||
assert.doesNotMatch(completedText, /Внешние действия не запускались/);
|
||||
|
||||
const cancelled = makeHarness();
|
||||
cancelled.operation.id = 'op-cancelled';
|
||||
cancelled.state.cancelReply = {ok: true, operation_id: 'op-cancelled', state: 'cancelled', uncertain: false, side_effect_started: false};
|
||||
await cancelled.driver.agentStop();
|
||||
const cancelledText = cancelled.state.texts.join('\n');
|
||||
assert.match(cancelledText, /остановлена на сервере/);
|
||||
assert.match(cancelledText, /Внешние действия не запускались/);
|
||||
});
|
||||
|
||||
test('agentStop keeps the manual-stop fast path for an operation the server never saw', async () => {
|
||||
const {driver, state, operation} = makeHarness();
|
||||
operation.id = 'op-unknown';
|
||||
// Real path: a send already failed (failureText set) and the user presses Stop.
|
||||
operation.failureText = 'Модель сейчас не ответила.';
|
||||
state.cancelReply = {ok: true, operation_id: 'op-unknown', state: 'not_found', uncertain: false};
|
||||
|
||||
await driver.agentStop();
|
||||
|
||||
const text = state.texts.join('\n');
|
||||
assert.match(text, /Запрос не был принят/);
|
||||
assert.match(text, /только вручную/);
|
||||
});
|
||||
@@ -0,0 +1,551 @@
|
||||
import ast
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for _path in (ROOT / "bot", ROOT / "gateway"):
|
||||
if str(_path) not in sys.path:
|
||||
sys.path.insert(0, str(_path))
|
||||
from assistant_runtime import AssistantError
|
||||
# [MODELMETA 2026-10-28] the extracted handler calls the real helper, which calls this
|
||||
# real module (static file, bounded cached read, never raises). Not stubbed.
|
||||
import model_metadata
|
||||
|
||||
SERVER = ROOT / "bot" / "webapp" / "server.py"
|
||||
SOURCE = SERVER.read_text(encoding="utf-8")
|
||||
TREE = ast.parse(SOURCE)
|
||||
|
||||
EXTRACTED = (
|
||||
"_model_metadata_rows",
|
||||
"_agent_key_limits_error",
|
||||
"_agent_key_model_limits",
|
||||
"_agent_models_for_key",
|
||||
"_agent_key_reject_details",
|
||||
"api_agent_models",
|
||||
"api_agent_chat",
|
||||
)
|
||||
|
||||
LOW = "deepseek-v4.1-flash-1017"
|
||||
MID = "grok-4.7"
|
||||
KIMI = "kimi/kimi-k3.1-pro"
|
||||
HIGH = "claude-opus-5-5"
|
||||
RANKED = [LOW, MID, KIMI]
|
||||
RANKS = {LOW: 1, MID: 1, KIMI: 1, HIGH: 3}
|
||||
|
||||
SLASH = "kimi/kimi-k3.1-pro"
|
||||
SLASH_HS = "kimi/kimi-k3.1-pro-highspeed"
|
||||
FLAT = "kimi-k3.1-pro"
|
||||
FLAT_HS = "kimi-k3.1-pro-highspeed"
|
||||
# [KEYGATE 2810] форма живого каталога активного бота: Kimi 3.1 только плоскими именами.
|
||||
LIVE_TIERS = {
|
||||
1: [LOW],
|
||||
2: [MID, "gpt-5.6-sol"],
|
||||
3: [FLAT, FLAT_HS],
|
||||
4: [HIGH],
|
||||
}
|
||||
|
||||
|
||||
def _json_response(payload, status=200):
|
||||
return SimpleNamespace(payload=payload, status=status)
|
||||
|
||||
|
||||
WEB = SimpleNamespace(json_response=_json_response)
|
||||
|
||||
|
||||
def _load(runtime, allowed=None, pool=None, min_ranks=None, body=None, rank_aware=False):
|
||||
allowed = list(RANKED if allowed is None else allowed)
|
||||
pool = list(allowed if pool is None else pool)
|
||||
min_ranks = dict(RANKS if min_ranks is None else min_ranks)
|
||||
|
||||
def refresh():
|
||||
return {"source": "live"}
|
||||
|
||||
def models_for(rank):
|
||||
if rank_aware:
|
||||
return [name for name in allowed if min_ranks.get(name, 1) <= rank]
|
||||
return list(allowed)
|
||||
|
||||
def pool_models():
|
||||
return list(pool)
|
||||
|
||||
def min_rank(name):
|
||||
return min_ranks.get(name)
|
||||
|
||||
def rank_name(value):
|
||||
return {1: "Старт", 2: "Про", 3: "Бизнес"}.get(value, "—")
|
||||
|
||||
async def json_body(_req):
|
||||
return dict(body or {})
|
||||
|
||||
namespace = {
|
||||
"_ASSISTANT": runtime,
|
||||
"_refresh_bot_catalog": refresh,
|
||||
"_agent_models_for": models_for,
|
||||
"_agent_pool": pool_models,
|
||||
"_model_min_rank": min_rank,
|
||||
"_rank_name": rank_name,
|
||||
"_json_body": json_body,
|
||||
# Production adds read-only route/health decoration; admission assertions
|
||||
# must also run on that exact payload without making provider probes.
|
||||
"_chat_route_snapshot": lambda names: ({name: True for name in names}, {}),
|
||||
"_catalogue_model_state": lambda name, rank, configured, status, now: {
|
||||
"name": name, "entitled": min_rank(name) <= rank,
|
||||
},
|
||||
"_MS": {"data": {}},
|
||||
"time": SimpleNamespace(time=lambda: 0),
|
||||
"asyncio": asyncio,
|
||||
"os": os,
|
||||
"web": WEB,
|
||||
"sqlite3": sqlite3,
|
||||
"closing": closing,
|
||||
"AssistantError": AssistantError,
|
||||
"model_metadata": model_metadata,
|
||||
}
|
||||
nodes = [node for node in TREE.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in EXTRACTED]
|
||||
assert {node.name for node in nodes} == set(EXTRACTED), "server functions moved: update EXTRACTED"
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(SERVER), "exec"), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
def _rank_lookup(tiers):
|
||||
"""Real _model_min_rank + its canonical twin table, executed against given tiers."""
|
||||
nodes = []
|
||||
for node in TREE.body:
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_model_min_rank":
|
||||
nodes.append(node)
|
||||
elif isinstance(node, ast.Assign) and any(
|
||||
isinstance(target, ast.Name) and target.id == "_SLASH_RANK_TWINS"
|
||||
for target in node.targets):
|
||||
nodes.append(node)
|
||||
assert len(nodes) == 2, "server rank fallback moved: update _rank_lookup"
|
||||
# Preserve the live Opus-floor constant when executing its rank method.
|
||||
# Canonical source without this production-only guard needs no substitute.
|
||||
for node in TREE.body:
|
||||
if isinstance(node, ast.Assign) and any(
|
||||
isinstance(target, ast.Name) and target.id == "OPUS_MIN_RANK"
|
||||
for target in node.targets):
|
||||
nodes.insert(0, node)
|
||||
namespace = {"TIER_MODELS": tiers}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(SERVER), "exec"), namespace)
|
||||
return namespace["_model_min_rank"]
|
||||
|
||||
|
||||
class Req(dict):
|
||||
def __init__(self, data):
|
||||
super().__init__(data)
|
||||
self.app = {}
|
||||
self.transport = None
|
||||
|
||||
|
||||
class _RecordingConnection(sqlite3.Connection):
|
||||
"""Captures the SQL template and bound parameters before sqlite expands them."""
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
self.records.append((sql, params))
|
||||
return super().execute(sql, params)
|
||||
|
||||
|
||||
class FakeRuntime:
|
||||
def __init__(self, newapi_db):
|
||||
self.newapi_db = Path(newapi_db)
|
||||
self.key = "sk-livecred"
|
||||
self.user_key_error = None
|
||||
self.chat_calls = []
|
||||
self.models = [LOW]
|
||||
self.operations = {}
|
||||
self.finished = {}
|
||||
self.records = []
|
||||
|
||||
def user_key(self, uid):
|
||||
if self.user_key_error is not None:
|
||||
raise self.user_key_error
|
||||
return self.key
|
||||
|
||||
def connect(self, path):
|
||||
con = sqlite3.connect(str(path), timeout=5, factory=_RecordingConnection)
|
||||
con.records = self.records
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
|
||||
def operation_id(self, value, generate=False):
|
||||
return value or "op-test"
|
||||
|
||||
async def chat(self, uid, payload, alive=None):
|
||||
self.chat_calls.append((uid, dict(payload)))
|
||||
return {"ok": True, "model": payload.get("model")}
|
||||
|
||||
|
||||
class AgentModelAccessTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.db = Path(self.tmp.name) / "newapi.db"
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute(
|
||||
"CREATE TABLE tokens(id INTEGER PRIMARY KEY,name TEXT,key TEXT,status INTEGER,"
|
||||
"deleted_at INTEGER,remain_quota INTEGER,model_limits_enabled,"
|
||||
"model_limits)")
|
||||
self.runtime = FakeRuntime(self.db)
|
||||
|
||||
# -- fixtures ---------------------------------------------------------
|
||||
def token(self, key, *, name="tg42-k1", status=1, deleted=None, enabled=0,
|
||||
limits="", quota=100):
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute(
|
||||
"INSERT INTO tokens(name,key,status,deleted_at,remain_quota,"
|
||||
"model_limits_enabled,model_limits) VALUES(?,?,?,?,?,?,?)",
|
||||
(name, key, status, deleted, quota, enabled, limits))
|
||||
|
||||
def use_key(self, plain):
|
||||
self.runtime.key = plain if plain.startswith("sk-") else "sk-" + plain
|
||||
return self.runtime.key
|
||||
|
||||
def env(self, **kwargs):
|
||||
return _load(self.runtime, **kwargs)
|
||||
|
||||
def read_limits(self, **kwargs):
|
||||
return self.env(**kwargs)["_agent_key_model_limits"](42)
|
||||
|
||||
def assert_key_error(self, exc, status, code):
|
||||
self.assertIsInstance(exc, AssistantError)
|
||||
self.assertEqual((exc.status, exc.code), (status, code))
|
||||
|
||||
# -- ACL parsing ------------------------------------------------------
|
||||
def test_disabled_whitelist_keeps_rank_filtered_candidates(self):
|
||||
self.token("livecred", enabled=0, limits=MID)
|
||||
found = self.read_limits()
|
||||
self.assertIsNone(found)
|
||||
self.assertEqual(self.env()["_agent_models_for_key"](RANKED, found), RANKED)
|
||||
|
||||
def test_enabled_csv_is_exact_intersection_in_rank_order(self):
|
||||
self.token("livecred", enabled=1, limits=" %s , %s ,ghost-model " % (KIMI, MID))
|
||||
found = self.read_limits()
|
||||
self.assertEqual(found, frozenset({KIMI, MID, "ghost-model"}))
|
||||
self.assertEqual(self.env()["_agent_models_for_key"](RANKED, found), [MID, KIMI])
|
||||
|
||||
def test_alias_and_case_are_not_expanded(self):
|
||||
self.token("livecred", enabled=1,
|
||||
limits="deepseek-v4.1-flash,grok-4.7-chat,DEEPSEEK-V4.1-FLASH-1017")
|
||||
found = self.read_limits()
|
||||
self.assertNotIn(LOW, found)
|
||||
self.assertNotIn(MID, found)
|
||||
self.assertEqual(self.env()["_agent_models_for_key"](RANKED, found), [])
|
||||
|
||||
def test_enabled_empty_or_separator_only_whitelist_denies_everything(self):
|
||||
self.token("empty1", enabled=1, limits="")
|
||||
self.use_key("empty1")
|
||||
self.assertEqual(self.read_limits(), frozenset())
|
||||
self.token("empty2", enabled=1, limits=" , , ")
|
||||
self.use_key("empty2")
|
||||
self.assertEqual(self.read_limits(), frozenset())
|
||||
|
||||
def test_malformed_flag_fails_closed(self):
|
||||
cases = (None, "1", "0", 2, -1, 1.5, b"1")
|
||||
for index, value in enumerate(cases):
|
||||
plain = "flag%d" % index
|
||||
self.token(plain, enabled=value)
|
||||
self.use_key(plain)
|
||||
with self.subTest(value=value):
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 503, "key_limits_unavailable")
|
||||
|
||||
def test_malformed_limits_fail_closed(self):
|
||||
cases = (None, 5, b"grok-4.7")
|
||||
for index, value in enumerate(cases):
|
||||
plain = "bad%d" % index
|
||||
self.token(plain, enabled=1, limits=value)
|
||||
self.use_key(plain)
|
||||
with self.subTest(value=value):
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 503, "key_limits_unavailable")
|
||||
|
||||
# -- credential resolution -------------------------------------------
|
||||
def test_missing_row_fails_closed(self):
|
||||
self.token("gone", status=0)
|
||||
self.token("sk-gone", deleted=123, enabled=1, limits=MID)
|
||||
self.use_key("gone")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 403, "key_ambiguous")
|
||||
|
||||
def test_ambiguous_rows_fail_closed(self):
|
||||
self.token("dup", enabled=1, limits=MID)
|
||||
self.token("sk-dup", name="tg42-k2", enabled=1, limits=HIGH)
|
||||
self.use_key("dup")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 403, "key_ambiguous")
|
||||
|
||||
def test_deleted_or_inactive_duplicate_is_ignored(self):
|
||||
self.token("keep", enabled=1, limits=MID)
|
||||
self.token("sk-keep", name="tg42-k2", status=0, deleted=99, enabled=1, limits=HIGH)
|
||||
self.use_key("keep")
|
||||
self.assertEqual(self.read_limits(), frozenset({MID}))
|
||||
|
||||
def test_only_the_runtime_credential_is_queried(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
self.token("othertoken", name="tg99-k1", enabled=1, limits=HIGH)
|
||||
self.assertEqual(self.read_limits(), frozenset({MID}))
|
||||
statements = [(sql, params) for sql, params in self.runtime.records
|
||||
if sql.strip().upper().startswith("SELECT")]
|
||||
self.assertEqual(len(statements), 1)
|
||||
query, params = statements[0]
|
||||
self.assertIn("key IN (?,?)", query)
|
||||
self.assertEqual(sorted(params), ["livecred", "sk-livecred"])
|
||||
self.assertIn("status=1", query)
|
||||
self.assertIn("deleted_at IS NULL", query)
|
||||
self.assertIn("LIMIT 2", query)
|
||||
self.assertNotIn("othertoken", query)
|
||||
self.assertNotIn("othertoken", " ".join(map(str, params)))
|
||||
self.assertNotIn("name =", query)
|
||||
|
||||
def test_database_errors_fail_closed(self):
|
||||
broken = Path(self.tmp.name) / "broken.db"
|
||||
with closing(sqlite3.connect(broken)) as con, con:
|
||||
con.execute("CREATE TABLE unrelated(x INTEGER)")
|
||||
self.runtime.newapi_db = broken
|
||||
self.use_key("whatever")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 503, "key_limits_unavailable")
|
||||
|
||||
self.runtime.newapi_db = self.db
|
||||
self.runtime.user_key_error = sqlite3.OperationalError("database is locked")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 503, "key_limits_unavailable")
|
||||
|
||||
def test_existing_credential_errors_stay_meaningful(self):
|
||||
for code in ("key_locked", "need_key", "access_blocked", "need_start"):
|
||||
self.runtime.user_key_error = AssistantError(403, code, "нет доступа")
|
||||
with self.subTest(code=code):
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.read_limits()
|
||||
self.assert_key_error(caught.exception, 403, code)
|
||||
|
||||
def test_no_database_mutations(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
self.token("spare", name="tg42-k2", enabled=1, limits=HIGH)
|
||||
before = self.db.read_bytes()
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
rows_before = con.execute("SELECT * FROM tokens ORDER BY id").fetchall()
|
||||
self.assertEqual(self.read_limits(), frozenset({MID}))
|
||||
self.assertEqual(self.db.read_bytes(), before)
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
self.assertEqual(con.execute("SELECT * FROM tokens ORDER BY id").fetchall(), rows_before)
|
||||
|
||||
# -- GET /api/agent/models -------------------------------------------
|
||||
def test_models_endpoint_reports_key_limit_and_keeps_rank_locked(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
env = self.env(pool=RANKED + [HIGH])
|
||||
response = asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1})))
|
||||
payload = response.payload
|
||||
self.assertEqual(payload["models"], [MID])
|
||||
self.assertEqual([item["name"] for item in payload["locked"]], [HIGH])
|
||||
self.assertEqual(payload["key_unavailable"],
|
||||
[{"name": LOW, "reason": "key_model_limit"},
|
||||
{"name": KIMI, "reason": "key_model_limit"}])
|
||||
self.assertNotIn("msg", payload)
|
||||
dumped = json.dumps(payload, ensure_ascii=False)
|
||||
self.assertNotIn("livecred", dumped)
|
||||
self.assertNotIn("sk-", dumped)
|
||||
|
||||
def test_models_endpoint_without_key_limits_keeps_full_rank_list(self):
|
||||
self.token("livecred", enabled=0, limits=HIGH)
|
||||
env = self.env()
|
||||
payload = asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1}))).payload
|
||||
self.assertEqual(payload["models"], RANKED)
|
||||
self.assertEqual(payload["key_unavailable"], [])
|
||||
self.assertNotIn("msg", payload)
|
||||
|
||||
def test_models_endpoint_empty_intersection_returns_honest_message(self):
|
||||
self.token("livecred", enabled=1, limits="ghost-model")
|
||||
env = self.env()
|
||||
payload = asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1}))).payload
|
||||
self.assertEqual(payload["models"], [])
|
||||
self.assertTrue(payload["msg"])
|
||||
self.assertIn("API-ключ", payload["msg"])
|
||||
self.assertEqual([item["name"] for item in payload["key_unavailable"]], RANKED)
|
||||
dumped = json.dumps(payload, ensure_ascii=False)
|
||||
self.assertNotIn("livecred", dumped)
|
||||
self.assertNotIn("ghost-model", dumped)
|
||||
|
||||
def test_acl_change_is_observed_by_the_next_request(self):
|
||||
# поэтому ACL читается на каждый запрос и нигде не кэшируется.
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
env = self.env()
|
||||
first = asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1}))).payload
|
||||
self.assertEqual(first["models"], [MID])
|
||||
self.assertEqual([item["name"] for item in first["key_unavailable"]], [LOW, KIMI])
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute("UPDATE tokens SET model_limits=? WHERE key=?",
|
||||
("%s,%s" % (LOW, KIMI), "livecred"))
|
||||
second = asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1}))).payload
|
||||
self.assertEqual(second["models"], [LOW, KIMI])
|
||||
self.assertEqual([item["name"] for item in second["key_unavailable"]], [MID])
|
||||
chat = self.env(body={"model": MID, "messages": [{"role": "user", "content": "привет"}]})
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
asyncio.run(chat["api_agent_chat"](Req({"uid": 42, "rank": 1})))
|
||||
self.assert_key_error(caught.exception, 403, "model_key_access")
|
||||
self.assertEqual(self.runtime.chat_calls, [])
|
||||
|
||||
def test_models_endpoint_surfaces_key_state_error(self):
|
||||
self.runtime.user_key_error = AssistantError(403, "key_locked", "Ключ заблокирован")
|
||||
env = self.env()
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
asyncio.run(env["api_agent_models"](Req({"uid": 42, "rank": 1})))
|
||||
self.assert_key_error(caught.exception, 403, "key_locked")
|
||||
|
||||
# -- POST /api/agent/chat --------------------------------------------
|
||||
def post(self, model, uid=42, rank=1, operation_id=None, **kwargs):
|
||||
body = {"model": model, "messages": [{"role": "user", "content": "привет"}]}
|
||||
if operation_id is not None:
|
||||
body["operation_id"] = operation_id
|
||||
env = self.env(body=body, **kwargs)
|
||||
return asyncio.run(env["api_agent_chat"](Req({"uid": uid, "rank": rank})))
|
||||
|
||||
def test_explicit_model_blocked_by_key_never_reaches_runtime(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post(KIMI)
|
||||
self.assert_key_error(caught.exception, 403, "model_key_access")
|
||||
self.assertIn(KIMI, caught.exception.message)
|
||||
self.assertIn("API-ключ", caught.exception.message)
|
||||
self.assertNotIn("Telegram", caught.exception.message)
|
||||
self.assertEqual(self.runtime.chat_calls, [])
|
||||
|
||||
def test_explicit_model_allowed_by_key_is_not_substituted(self):
|
||||
self.token("livecred", enabled=1, limits=KIMI)
|
||||
self.post(KIMI)
|
||||
self.assertEqual(len(self.runtime.chat_calls), 1)
|
||||
uid, payload = self.runtime.chat_calls[0]
|
||||
self.assertEqual(uid, 42)
|
||||
self.assertEqual(payload["model"], KIMI)
|
||||
self.assertNotIn("candidates", payload)
|
||||
|
||||
def test_auto_candidates_are_only_key_permitted_models(self):
|
||||
self.token("livecred", enabled=1, limits="%s,%s" % (KIMI, LOW))
|
||||
self.post("auto")
|
||||
uid, payload = self.runtime.chat_calls[0]
|
||||
self.assertEqual(payload["model"], "auto")
|
||||
self.assertEqual(payload["candidates"], [LOW, KIMI])
|
||||
|
||||
def test_pre_admission_rejection_carries_safe_not_found_receipt(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post(KIMI, operation_id="op-fresh")
|
||||
details = caught.exception.details
|
||||
self.assertEqual(details["operation_id"], "op-fresh")
|
||||
self.assertEqual(details["state"], "not_found")
|
||||
self.assertIs(details["uncertain"], False)
|
||||
self.assertIs(details["side_effect_started"], False)
|
||||
|
||||
def test_replayed_operation_id_gets_no_not_found_receipt(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
self.runtime.finished[(42, "op-done")] = {
|
||||
"state": "completed", "uncertain": False, "side_effect_started": True,
|
||||
"finished_at": 0.0}
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post(KIMI, operation_id="op-done")
|
||||
self.assertEqual(caught.exception.details, {"operation_id": "op-done"})
|
||||
|
||||
def test_running_same_operation_gets_no_not_found_receipt(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
self.runtime.operations[42] = SimpleNamespace(operation_id="op-running")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post(KIMI, operation_id="op-running")
|
||||
self.assertNotIn("state", caught.exception.details)
|
||||
|
||||
def test_auto_without_permitted_candidate_fails_closed(self):
|
||||
self.token("livecred", enabled=1, limits="ghost-model")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post("auto")
|
||||
self.assert_key_error(caught.exception, 403, "model_key_access")
|
||||
self.assertEqual(caught.exception.details.get("state"), "not_found")
|
||||
self.assertEqual(self.runtime.chat_calls, [])
|
||||
|
||||
def test_auto_with_empty_whitelist_fails_closed(self):
|
||||
self.token("livecred", enabled=1, limits="")
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
self.post("auto")
|
||||
self.assert_key_error(caught.exception, 403, "model_key_access")
|
||||
self.assertEqual(self.runtime.chat_calls, [])
|
||||
|
||||
def test_disabled_whitelist_keeps_all_rank_candidates_for_auto(self):
|
||||
self.token("livecred", enabled=0, limits="ghost-model")
|
||||
self.post("auto")
|
||||
uid, payload = self.runtime.chat_calls[0]
|
||||
self.assertEqual(payload["candidates"], RANKED)
|
||||
|
||||
def test_chat_does_not_mutate_database(self):
|
||||
self.token("livecred", enabled=1, limits=MID)
|
||||
before = self.db.read_bytes()
|
||||
self.post(MID)
|
||||
self.assertEqual(self.db.read_bytes(), before)
|
||||
|
||||
|
||||
|
||||
class ModelMinRankTests(unittest.TestCase):
|
||||
"""[KEYGATE 2810] canonical slash Kimi 3.1 -> flat tier twin, exact precedence, no widening."""
|
||||
|
||||
def test_flat_only_live_tiers_rank_canonical_slash_kimi(self):
|
||||
rank = _rank_lookup(LIVE_TIERS)
|
||||
self.assertEqual(rank(SLASH), 3)
|
||||
self.assertEqual(rank(SLASH_HS), 3)
|
||||
self.assertEqual(rank(FLAT), 3)
|
||||
self.assertEqual(rank(HIGH), 4) # Opus floor untouched
|
||||
self.assertIsNone(rank("kimi/kimi-k3.1-pro-preview"))
|
||||
self.assertIsNone(rank("foo/bar"))
|
||||
self.assertIsNone(rank("kimi-k3.1-pro-max"))
|
||||
|
||||
def test_exact_tier_beats_flat_twin(self):
|
||||
rank = _rank_lookup({2: [SLASH], 4: [FLAT, FLAT_HS]})
|
||||
self.assertEqual(rank(SLASH), 2)
|
||||
self.assertEqual(rank(FLAT), 4)
|
||||
self.assertEqual(rank(SLASH_HS), 4)
|
||||
|
||||
def test_no_reverse_mapping_from_slash_to_flat(self):
|
||||
rank = _rank_lookup({3: [SLASH, SLASH_HS]})
|
||||
self.assertEqual(rank(SLASH), 3)
|
||||
self.assertIsNone(rank(FLAT))
|
||||
self.assertIsNone(rank(FLAT_HS))
|
||||
|
||||
def test_slash_rank_gate_2_denied_3_allowed_and_model_unchanged(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = Path(tmp) / "newapi.db"
|
||||
with closing(sqlite3.connect(db)) as con, con:
|
||||
con.execute(
|
||||
"CREATE TABLE tokens(id INTEGER PRIMARY KEY,name TEXT,key TEXT,status INTEGER,"
|
||||
"deleted_at INTEGER,remain_quota INTEGER,model_limits_enabled,model_limits)")
|
||||
con.execute(
|
||||
"INSERT INTO tokens(name,key,status,deleted_at,remain_quota,"
|
||||
"model_limits_enabled,model_limits) VALUES(?,?,?,?,?,?,?)",
|
||||
("tg42-k1", "livecred", 1, None, 100, 1, "%s,%s" % (SLASH, SLASH_HS)))
|
||||
runtime = FakeRuntime(db)
|
||||
derived = _rank_lookup(LIVE_TIERS)
|
||||
self.assertEqual(derived(SLASH), 3)
|
||||
kwargs = dict(allowed=[LOW, SLASH], pool=[LOW, SLASH],
|
||||
min_ranks={LOW: 1, SLASH: 3}, rank_aware=True)
|
||||
body = {"model": SLASH, "messages": [{"role": "user", "content": "привет"}]}
|
||||
env = _load(runtime, body=body, **kwargs)
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
asyncio.run(env["api_agent_chat"](Req({"uid": 42, "rank": 2})))
|
||||
self.assertEqual((caught.exception.status, caught.exception.code), (403, "model_rank"))
|
||||
self.assertEqual(runtime.chat_calls, [])
|
||||
asyncio.run(env["api_agent_chat"](Req({"uid": 42, "rank": 3})))
|
||||
self.assertEqual(len(runtime.chat_calls), 1)
|
||||
self.assertEqual(runtime.chat_calls[0][1]["model"], SLASH)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Terminal-truth receipts for the Mini App coding assistant.
|
||||
|
||||
The UI bug this guards against: a provider/model error *after* a successful tool call
|
||||
must not look like success, and must not let the client claim that no external actions
|
||||
ran. Receipts therefore carry an explicit `side_effect_started` boolean next to
|
||||
`uncertain`, and terminal failures report `state='failed'` (never 'completed').
|
||||
|
||||
These tests use the real chat()/_chat_work()/_finish_operation()/cancel() bodies; only the
|
||||
network edges (complete/execute/user_key) are scripted, so no provider or SQLite data is
|
||||
touched.
|
||||
"""
|
||||
import asyncio
|
||||
import importlib
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||||
sys.path.insert(0, str(BOT))
|
||||
runtime_module = importlib.import_module("assistant_runtime")
|
||||
AssistantError = runtime_module.AssistantError
|
||||
AssistantRuntime = runtime_module.AssistantRuntime
|
||||
|
||||
UID = 424242
|
||||
|
||||
|
||||
class ScriptedRuntime(AssistantRuntime):
|
||||
"""Real runtime, scripted edges: no provider, no sandbox, no database."""
|
||||
|
||||
def __init__(self, replies, exec_result=None, key_error=None):
|
||||
super().__init__("bot.db", "newapi.db", "http://127.0.0.1:9/v1", ("test-model",), None, None)
|
||||
self.replies = list(replies)
|
||||
self.exec_result = exec_result if exec_result is not None else {
|
||||
"cmd": "echo ok", "out": "ok", "exit_code": 0, "connected": True, "uncertain": False,
|
||||
}
|
||||
self.key_error = key_error
|
||||
self.complete_calls = []
|
||||
self.exec_calls = []
|
||||
|
||||
def user_key(self, uid):
|
||||
if self.key_error is not None:
|
||||
raise self.key_error
|
||||
return "sk-test-key"
|
||||
|
||||
async def complete(self, model, messages, key, *, fast=False, max_tokens=2048):
|
||||
self.complete_calls.append({"model": model, "fast": fast, "messages": list(messages)})
|
||||
if not self.replies:
|
||||
raise AssertionError("runtime asked for more upstream answers than the scenario provides")
|
||||
reply = self.replies.pop(0)
|
||||
if isinstance(reply, BaseException):
|
||||
raise reply
|
||||
return reply
|
||||
|
||||
async def execute(self, uid, command):
|
||||
self.exec_calls.append(command)
|
||||
return dict(self.exec_result)
|
||||
|
||||
|
||||
def payload(operation_id, text="привет"):
|
||||
return {
|
||||
"operation_id": operation_id,
|
||||
"model": "test-model",
|
||||
"messages": [{"role": "user", "content": text}],
|
||||
}
|
||||
|
||||
|
||||
class TerminalTruthTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
import os
|
||||
previous = os.environ.get("IISHKO_SANDBOX_ENABLED")
|
||||
os.environ["IISHKO_SANDBOX_ENABLED"] = "1"
|
||||
|
||||
def restore():
|
||||
if previous is None:
|
||||
os.environ.pop("IISHKO_SANDBOX_ENABLED", None)
|
||||
else:
|
||||
os.environ["IISHKO_SANDBOX_ENABLED"] = previous
|
||||
|
||||
self.addCleanup(restore)
|
||||
|
||||
def run_chat(self, runtime, operation_id, text="привет"):
|
||||
async def scenario():
|
||||
try:
|
||||
result = await runtime.chat(UID, payload(operation_id, text))
|
||||
except AssistantError as error:
|
||||
await asyncio.sleep(0) # let the done-callback publish the finished record
|
||||
return error
|
||||
await asyncio.sleep(0)
|
||||
return result
|
||||
|
||||
return asyncio.run(scenario())
|
||||
|
||||
def finished_record(self, runtime, operation_id):
|
||||
return runtime.finished.get((UID, operation_id))
|
||||
|
||||
def test_rejected_before_tool_is_failed_without_side_effects(self):
|
||||
"""403 from user_key: nothing ran, so the UI may restore the draft and retry."""
|
||||
refusal = AssistantError(403, "need_key", "Сначала создай активный API-ключ во вкладке «Ключи».")
|
||||
runtime = ScriptedRuntime(replies=[], key_error=refusal)
|
||||
error = self.run_chat(runtime, "op403beforetool")
|
||||
|
||||
self.assertIsInstance(error, AssistantError)
|
||||
self.assertEqual(error.status, 403)
|
||||
self.assertEqual(error.details.get("operation_id"), "op403beforetool")
|
||||
self.assertEqual(error.details.get("state"), "failed")
|
||||
self.assertIs(error.details.get("uncertain"), False)
|
||||
self.assertIs(error.details.get("side_effect_started"), False)
|
||||
self.assertEqual(runtime.complete_calls, [])
|
||||
self.assertEqual(runtime.exec_calls, [])
|
||||
|
||||
record = self.finished_record(runtime, "op403beforetool")
|
||||
self.assertIsNotNone(record, "a terminal failure must have a finished record")
|
||||
self.assertEqual(record["state"], "failed")
|
||||
self.assertIs(record["uncertain"], False)
|
||||
self.assertIs(record["side_effect_started"], False)
|
||||
|
||||
receipt = runtime.cancel(UID, "op403beforetool")
|
||||
# [CANCEL-COMPAT] legacy cancel whitelist: state stays terminal-but-known,
|
||||
# the failure itself rides in explicit markers.
|
||||
self.assertEqual(receipt["state"], "completed")
|
||||
self.assertIs(receipt.get("failed"), True)
|
||||
self.assertEqual(receipt.get("terminal_state"), "failed")
|
||||
self.assertIs(receipt["uncertain"], False)
|
||||
self.assertIs(receipt["side_effect_started"], False)
|
||||
self.assertNotIn("finished_at", receipt)
|
||||
|
||||
def test_failure_after_successful_tool_keeps_side_effect_truth(self):
|
||||
"""Model error after exec: state failed, side effects started, outcome uncertain."""
|
||||
runtime = ScriptedRuntime(
|
||||
replies=["<exec>echo ok</exec>", AssistantError(503, "model_unavailable", "Модель сейчас не ответила.")],
|
||||
exec_result={"cmd": "echo ok", "out": "ok", "exit_code": 0, "connected": True, "uncertain": False},
|
||||
)
|
||||
error = self.run_chat(runtime, "op503aftertool")
|
||||
|
||||
self.assertIsInstance(error, AssistantError)
|
||||
self.assertEqual(error.status, 503)
|
||||
self.assertEqual(error.details.get("state"), "failed")
|
||||
self.assertIs(error.details.get("uncertain"), True)
|
||||
self.assertIs(error.details.get("side_effect_started"), True)
|
||||
self.assertEqual(runtime.exec_calls, ["echo ok"])
|
||||
|
||||
record = self.finished_record(runtime, "op503aftertool")
|
||||
self.assertEqual(record["state"], "failed")
|
||||
self.assertIs(record["uncertain"], True)
|
||||
self.assertIs(record["side_effect_started"], True)
|
||||
|
||||
receipt = runtime.cancel(UID, "op503aftertool")
|
||||
# [CANCEL-COMPAT] legacy cancel whitelist: state stays terminal-but-known,
|
||||
# the failure itself rides in explicit markers.
|
||||
self.assertEqual(receipt["state"], "completed")
|
||||
self.assertIs(receipt.get("failed"), True)
|
||||
self.assertEqual(receipt.get("terminal_state"), "failed")
|
||||
self.assertIs(receipt["side_effect_started"], True)
|
||||
|
||||
def test_definitive_tool_then_answer_is_completed_not_uncertain(self):
|
||||
runtime = ScriptedRuntime(replies=["<exec>echo ok</exec>", "Готово: команда выполнена."])
|
||||
result = self.run_chat(runtime, "op200withtool")
|
||||
|
||||
self.assertNotIsInstance(result, BaseException)
|
||||
self.assertEqual(result["state"], "completed")
|
||||
self.assertIs(result["uncertain"], False)
|
||||
self.assertIs(result["side_effect_started"], True)
|
||||
self.assertIn("Готово", result["reply"])
|
||||
self.assertEqual(runtime.exec_calls, ["echo ok"])
|
||||
self.assertGreaterEqual(len(runtime.complete_calls), 2, "the tool result must be shown back to the model")
|
||||
|
||||
def test_unconfirmed_tool_answers_but_stays_uncertain(self):
|
||||
runtime = ScriptedRuntime(
|
||||
replies=["<exec>echo ok</exec>", "Не смог подтвердить результат."],
|
||||
exec_result={"cmd": "echo ok", "out": "VM не подтвердила завершение. Проверь файлы перед повтором.",
|
||||
"connected": False, "uncertain": True},
|
||||
)
|
||||
result = self.run_chat(runtime, "op200ambiguous")
|
||||
|
||||
self.assertNotIsInstance(result, BaseException)
|
||||
self.assertEqual(result["state"], "completed")
|
||||
self.assertIs(result["uncertain"], True)
|
||||
self.assertIs(result["side_effect_started"], True)
|
||||
self.assertTrue(result["reply"].strip())
|
||||
|
||||
def test_cancel_receipt_moves_from_requested_to_cancelled(self):
|
||||
class BlockingRuntime(ScriptedRuntime):
|
||||
def __init__(self):
|
||||
super().__init__(replies=["never returned"])
|
||||
self.entered = asyncio.Event()
|
||||
|
||||
async def complete(self, model, messages, key, *, fast=False, max_tokens=2048):
|
||||
self.entered.set()
|
||||
await asyncio.sleep(3600)
|
||||
raise AssertionError("unreachable")
|
||||
|
||||
async def scenario():
|
||||
runtime = BlockingRuntime()
|
||||
task = asyncio.create_task(runtime.chat(UID, payload("opcancelrunning")))
|
||||
await asyncio.wait_for(runtime.entered.wait(), 5)
|
||||
first = runtime.cancel(UID, "opcancelrunning")
|
||||
settled = await asyncio.wait_for(task, 5)
|
||||
return runtime, first, settled
|
||||
|
||||
runtime, first, settled = asyncio.run(scenario())
|
||||
self.assertEqual(first["state"], "cancel_requested")
|
||||
self.assertIs(first["uncertain"], False)
|
||||
|
||||
self.assertEqual(settled["state"], "cancelled")
|
||||
self.assertIs(settled.get("cancelled"), True)
|
||||
self.assertIs(settled["side_effect_started"], False)
|
||||
|
||||
record = self.finished_record(runtime, "opcancelrunning")
|
||||
self.assertEqual(record["state"], "cancelled")
|
||||
self.assertIs(record["side_effect_started"], False)
|
||||
|
||||
def test_unknown_operation_keeps_legacy_receipt_shape(self):
|
||||
"""No claim about side effects is made for an operation the server never saw."""
|
||||
runtime = ScriptedRuntime(replies=[])
|
||||
receipt = runtime.cancel(UID, "opunknownop")
|
||||
self.assertEqual(receipt, {"ok": True, "operation_id": "opunknownop",
|
||||
"state": "not_found", "uncertain": False})
|
||||
self.assertEqual(runtime._state("opx", "not_found"),
|
||||
{"ok": True, "operation_id": "opx", "state": "not_found", "uncertain": False})
|
||||
|
||||
def test_request_validation_rejection_is_not_stamped_as_failed(self):
|
||||
"""A 400 before an operation exists must not carry operation-level receipt fields."""
|
||||
runtime = ScriptedRuntime(replies=[])
|
||||
with self.assertRaises(AssistantError) as caught:
|
||||
asyncio.run(runtime.chat(UID, {"model": "nope", "messages": [{"role": "user", "content": "привет"}]}))
|
||||
details = getattr(caught.exception, "details", {}) or {}
|
||||
self.assertNotIn("state", details)
|
||||
self.assertNotIn("side_effect_started", details)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,44 @@
|
||||
from contextlib import closing
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
import rankings
|
||||
from test_http_contract import namespace
|
||||
|
||||
|
||||
class BalanceBoardTests(unittest.TestCase):
|
||||
def test_multiple_keys_and_duplicate_names_do_not_repeat_one_owner(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
bot, gateway = Path(directory)/'bot.db', Path(directory)/'gateway.db'
|
||||
with closing(sqlite3.connect(bot)) as con, con:
|
||||
con.executescript('CREATE TABLE users(tg_id INTEGER,username TEXT);'
|
||||
'CREATE TABLE econ_tx(src INTEGER,ts INTEGER,type TEXT);'
|
||||
"INSERT INTO users VALUES(42,'alice'),(43,NULL);")
|
||||
with closing(sqlite3.connect(gateway)) as con, con:
|
||||
con.execute('CREATE TABLE tokens(name TEXT,remain_quota INTEGER,status INTEGER,deleted_at INTEGER)')
|
||||
con.executemany('INSERT INTO tokens VALUES(?,?,?,?)', [
|
||||
('tg42',500_000,1,0), ('tg42',200_000,1,0),
|
||||
('pm42-k1',1_000_000,4,None), ('sol42-k2',500_000,1,0),
|
||||
('tg43',1_000_000,1,0), ('tg42evil',99_000_000,1,0),
|
||||
('tg042',99_000_000,1,0), ('tg42-k0',99_000_000,1,0),
|
||||
('tg42-k3',99_000_000,2,0), ('pm42-k4',99_000_000,1,100)])
|
||||
def connect(path):
|
||||
con = sqlite3.connect(path)
|
||||
con.row_factory = sqlite3.Row
|
||||
return con
|
||||
env = namespace(['_boards_sync'], _con=connect, rankings=rankings,
|
||||
time=time, QUOTA_PER_USD=500_000)
|
||||
env.update(BOT_DB=str(bot), NEWAPI_DB=str(gateway))
|
||||
result, code = env['_boards_sync']()
|
||||
self.assertEqual(code,200)
|
||||
self.assertEqual(len(result['rich']),2)
|
||||
self.assertEqual(result['rich'][0],{'pos':1,'user':'@alice','usd':4.0})
|
||||
self.assertTrue(result['rich'][1]['user'].startswith('user-'))
|
||||
self.assertEqual(result['casino'],[])
|
||||
self.assertFalse(any('uid' in row or 'tg_id' in row for row in result['rich']))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Provider policy failures must remain actionable, terminal and non-replayed."""
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from test_bot_stability import Session, Response, actual_gateway, frame
|
||||
|
||||
|
||||
class ContentPolicyContracts(unittest.IsolatedAsyncioTestCase):
|
||||
def response(self, *, status=400, code="data_inspection_failed", stream=False, prefix=""):
|
||||
body = {"error": {"message": prefix + "private-provider-text", "code": code, "request_id": "Policy-Trace-123"}}
|
||||
if stream:
|
||||
return Response([("data: " + json.dumps(body) + "\n\n").encode()])
|
||||
response = Response(status=status, body=body)
|
||||
async def read(size):
|
||||
return json.dumps(body).encode()[:size]
|
||||
response.content.read = read
|
||||
return response
|
||||
|
||||
async def assert_policy(self, response, streaming):
|
||||
session = Session([response])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text):
|
||||
pass
|
||||
with self.assertRaises(RuntimeError) as caught:
|
||||
if streaming:
|
||||
await ns["gw_chat_stream"]([], "model-x", send)
|
||||
else:
|
||||
await ns["gw_call"]("/chat/completions", {"model": "model-x"})
|
||||
error = caught.exception
|
||||
self.assertTrue(getattr(error, "terminal", False))
|
||||
self.assertTrue(getattr(error, "content_policy", False))
|
||||
self.assertEqual(getattr(error, "status", None), 400)
|
||||
self.assertFalse(getattr(error, "retry_safe", True))
|
||||
self.assertFalse(getattr(error, "stability_dependency_failure", True))
|
||||
self.assertIn("контент-фильтр", str(error))
|
||||
self.assertNotIn("private-provider-text", str(error))
|
||||
self.assertEqual(getattr(error, "request_id", None), "Policy-Trace-123")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(session.calls[0][1]["json"]["model"], "model-x")
|
||||
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0)
|
||||
|
||||
async def test_nonstream_code_only_policy_is_terminal_without_model_penalty(self):
|
||||
await self.assert_policy(self.response(), False)
|
||||
|
||||
async def test_http_stream_policy_preserves_reason(self):
|
||||
await self.assert_policy(self.response(), True)
|
||||
|
||||
async def test_sse_error_frame_policy_preserves_reason(self):
|
||||
await self.assert_policy(self.response(stream=True), True)
|
||||
|
||||
async def test_long_policy_body_not_truncated_before_code(self):
|
||||
await self.assert_policy(self.response(prefix="x" * 700), True)
|
||||
|
||||
async def test_normalized_policy_code_is_recognized(self):
|
||||
await self.assert_policy(self.response(code="content_policy_violation"), False)
|
||||
|
||||
async def test_wrapped_503_policy_not_retried_as_outage(self):
|
||||
await self.assert_policy(self.response(status=503), True)
|
||||
|
||||
async def test_unsupported_content_filter_parameter_not_a_policy_failure(self):
|
||||
response = self.response(code="unsupported_parameter", prefix="content_filter unsupported: ")
|
||||
session = Session([response])
|
||||
ns, _ = actual_gateway(session)
|
||||
with self.assertRaises(RuntimeError) as caught:
|
||||
await ns["gw_call"]("/chat/completions", {"model": "model-x"})
|
||||
self.assertFalse(getattr(caught.exception, "content_policy", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
|
||||
async def test_partial_policy_failure_never_replays_generated_content(self):
|
||||
response = self.response(stream=True)
|
||||
response.content.frames.insert(0, frame("already generated"))
|
||||
session = Session([response])
|
||||
ns, gate = actual_gateway(session)
|
||||
sent = []
|
||||
async def send(text):
|
||||
sent.append(text)
|
||||
result = await ns["gw_chat_stream"]([], "model-x", send)
|
||||
self.assertIn("already generated", result)
|
||||
self.assertTrue(getattr(result, "incomplete", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0)
|
||||
self.assertTrue(sent)
|
||||
|
||||
async def test_sse_filtered_finish_is_partial_not_success(self):
|
||||
session = Session([Response([frame("partial text", finish="content_filter")])])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text):
|
||||
pass
|
||||
result = await ns["gw_chat_stream"]([], "model-x", send)
|
||||
self.assertEqual(str(result), "partial text")
|
||||
self.assertTrue(getattr(result, "incomplete", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 0)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0)
|
||||
|
||||
async def test_nonstream_filtered_finish_is_not_an_empty_outage(self):
|
||||
response = Response(body={"choices": [
|
||||
{"message": {"content": None}, "finish_reason": "content_filter"}
|
||||
]})
|
||||
session = Session([response])
|
||||
ns, gate = actual_gateway(session)
|
||||
with self.assertRaises(RuntimeError) as caught:
|
||||
await ns["gw_chat"]([], "model-x")
|
||||
self.assertTrue(getattr(caught.exception, "content_policy", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Offline contracts for the production dead-model routing incident.
|
||||
|
||||
Only selected assignments/functions are executed: importing the bot would start
|
||||
application resources and is deliberately avoided.
|
||||
"""
|
||||
import ast
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||||
SOURCE = (BOT / "grok_bot.py").read_text(encoding="utf-8")
|
||||
TREE = ast.parse(SOURCE)
|
||||
DEAD = "deepseek-v4.1-flash"
|
||||
LIVE = "deepseek-v4.1-flash-1017"
|
||||
KIMI = "kimi/kimi-k3.1-pro"
|
||||
CATALOGUE_ASSIGNMENTS = {
|
||||
"TIER_MODELS", "MODEL_DESCS", "MODEL_ALIAS", "CHAT_MODELS",
|
||||
"CHAT_FREE_MODELS", "CHAT_PICKER_MODELS", "SMART_UPGRADE_MODEL",
|
||||
"AGENT_MODELS", "PREMIUM_WEEKS", "TIER_UNLOCK", "CHAT_FALLBACK",
|
||||
}
|
||||
|
||||
|
||||
def catalogue():
|
||||
selected: list[ast.stmt] = [
|
||||
node for node in TREE.body
|
||||
if isinstance(node, ast.Assign)
|
||||
and len(node.targets) == 1
|
||||
and isinstance(node.targets[0], ast.Name)
|
||||
and node.targets[0].id in CATALOGUE_ASSIGNMENTS
|
||||
]
|
||||
namespace = {}
|
||||
exec(compile(ast.Module(body=selected, type_ignores=[]), "<catalogue>", "exec"), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
class BotModelRouting(unittest.TestCase):
|
||||
def test_catalogue_expression_executes_with_integer_rank_keys(self):
|
||||
ns = catalogue()
|
||||
tiers = ns["TIER_MODELS"]
|
||||
self.assertEqual(set(tiers), {1, 2, 3, 4})
|
||||
self.assertTrue(all(type(rank) is int for rank in tiers))
|
||||
expected = list(dict.fromkeys(model for rank in (1, 2, 3, 4) for model in tiers[rank]))
|
||||
self.assertEqual(ns["CHAT_MODELS"], expected)
|
||||
self.assertNotIn(DEAD, expected)
|
||||
|
||||
def test_exact_live_default_is_rank_one_and_kimi_rank_is_preserved(self):
|
||||
ns = catalogue()
|
||||
example = json.loads((BOT / "config.example.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(example["chat_default_model"], LIVE)
|
||||
self.assertIn(LIVE, ns["CHAT_FREE_MODELS"])
|
||||
self.assertEqual(min(rank for rank, models in ns["TIER_MODELS"].items() if KIMI in models), 3)
|
||||
|
||||
def test_repair_does_not_add_premium_requirements_or_silent_fallbacks(self):
|
||||
ns = catalogue()
|
||||
self.assertNotIn(LIVE, ns["PREMIUM_WEEKS"])
|
||||
self.assertEqual(set(ns["TIER_UNLOCK"]), set(ns["TIER_MODELS"]))
|
||||
self.assertEqual(ns["CHAT_FALLBACK"], [])
|
||||
|
||||
def test_miniapp_cold_start_catalogue_does_not_offer_dead_models(self):
|
||||
source = (BOT / "webapp" / "server.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
fallback = {}
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
|
||||
continue
|
||||
target = node.targets[0]
|
||||
if isinstance(target, ast.Name) and target.id in {"TIER_MODELS", "MODEL_DESCS", "AGENT_MODELS_WA"}:
|
||||
fallback[target.id] = ast.literal_eval(node.value)
|
||||
tiers = fallback["TIER_MODELS"]
|
||||
models = [model for rank in (1, 2, 3, 4) for model in tiers[rank]]
|
||||
for dead in (DEAD, "deepseek-v4-flash"):
|
||||
self.assertNotIn(dead, models)
|
||||
self.assertNotIn(dead, fallback["AGENT_MODELS_WA"])
|
||||
self.assertNotIn(DEAD, fallback["MODEL_DESCS"])
|
||||
self.assertIn(LIVE, tiers[1])
|
||||
self.assertIn(KIMI, tiers[3])
|
||||
|
||||
def test_picker_and_agent_choices_have_no_duplicate_replacement(self):
|
||||
ns = catalogue()
|
||||
for name in ("CHAT_PICKER_MODELS", "AGENT_MODELS"):
|
||||
with self.subTest(collection=name):
|
||||
models = ns[name]
|
||||
self.assertNotIn(DEAD, models)
|
||||
self.assertEqual(models.count(LIVE), 1)
|
||||
self.assertEqual(len(models), len(set(models)))
|
||||
self.assertEqual(ns["MODEL_ALIAS"]["deepseek-v4-flash"], LIVE)
|
||||
self.assertEqual(ns["SMART_UPGRADE_MODEL"], LIVE)
|
||||
|
||||
def test_both_real_vision_handlers_call_the_exact_live_model(self):
|
||||
for name in ("handle_photo", "group_reply"):
|
||||
with self.subTest(handler=name):
|
||||
function = next(
|
||||
node for node in TREE.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == name
|
||||
)
|
||||
calls = [
|
||||
node for node in ast.walk(function)
|
||||
if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name) and node.func.id == "gw_chat"
|
||||
and len(node.args) >= 2 and isinstance(node.args[1], ast.Constant)
|
||||
and node.args[1].value == LIVE
|
||||
]
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
def test_dead_id_is_not_used_as_a_route_target(self):
|
||||
allowed_alias_keys = {
|
||||
id(key)
|
||||
for node in TREE.body
|
||||
if isinstance(node, ast.Assign)
|
||||
and any(isinstance(target, ast.Name) and target.id == "MODEL_ALIAS" for target in node.targets)
|
||||
and isinstance(node.value, ast.Dict)
|
||||
for key in node.value.keys
|
||||
if isinstance(key, ast.Constant) and key.value == DEAD
|
||||
}
|
||||
offending_lines = [
|
||||
node.lineno for node in ast.walk(TREE)
|
||||
if isinstance(node, ast.Constant) and node.value == DEAD and id(node) not in allowed_alias_keys
|
||||
]
|
||||
self.assertEqual(offending_lines, [])
|
||||
|
||||
def test_stale_preferences_heal_to_explicit_allowed_default(self):
|
||||
function = next(
|
||||
node for node in TREE.body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_live_chat_model"
|
||||
)
|
||||
saved = []
|
||||
ns = {
|
||||
"CFG": {"chat_default_model": LIVE},
|
||||
"rank_models": lambda uid: ["glm-5.3", LIVE],
|
||||
"db_set_pref": lambda uid, **prefs: saved.append((uid, prefs)),
|
||||
"log": logging.getLogger("test-model-routing"),
|
||||
}
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), "<resolver>", "exec"), ns)
|
||||
self.assertEqual(ns["_live_chat_model"](1, {"chat_model": DEAD}), LIVE)
|
||||
self.assertEqual(saved, [(1, {"chat_model": LIVE})])
|
||||
saved.clear()
|
||||
self.assertEqual(ns["_live_chat_model"](1, {"chat_model": None}), LIVE)
|
||||
self.assertEqual(saved, [])
|
||||
|
||||
def test_default_resolution_does_not_grant_a_model_outside_allowed_rank(self):
|
||||
function = next(
|
||||
node for node in TREE.body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_live_chat_model"
|
||||
)
|
||||
saved = []
|
||||
ns = {
|
||||
"CFG": {"chat_default_model": LIVE},
|
||||
"rank_models": lambda uid: ["glm-5.3"],
|
||||
"db_set_pref": lambda uid, **prefs: saved.append((uid, prefs)),
|
||||
"log": logging.getLogger("test-model-routing"),
|
||||
}
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), "<resolver>", "exec"), ns)
|
||||
self.assertEqual(ns["_live_chat_model"](1, {"chat_model": DEAD}), "glm-5.3")
|
||||
self.assertEqual(saved, [(1, {"chat_model": "glm-5.3"})])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Bot-owned migrations on real temporary SQLite files, never production DBs."""
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import bot_schema
|
||||
|
||||
# Literal legacy contract, deliberately independent of the migration's own list.
|
||||
EXPECTED_USER_COLUMNS = set("""
|
||||
tg_id username token_name api_key created notified points referred_by ref_time
|
||||
ref_awarded lang menu_style chat_mode waiting_prompt chat_count img_count quota_date
|
||||
chat_model img_model vip last_checkin last_loyalty admin captcha_ok banned week_model
|
||||
week_key last_active warned_at ref_credit key_locked rep quiz_last dice_last
|
||||
last_bonus_lvl rep_last badge_lock last_bonus_ts rank_cache ref_notify vid_model
|
||||
mus_model sub_penalized rep_give_day rep_give_n api_blocked api_block_reason
|
||||
gate_member_ok gate_member_ts gate_warned_at agent_model effort prompt_on badge_until
|
||||
""".split())
|
||||
|
||||
|
||||
def test_fresh_database_has_complete_versioned_schema_and_indexed_hot_paths(tmp_path):
|
||||
path = tmp_path / "bot.db"
|
||||
bot_schema.initialize_bot_db(path)
|
||||
with sqlite3.connect(path) as con:
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == bot_schema.SCHEMA_VERSION
|
||||
columns = {row[1] for row in con.execute("PRAGMA table_info(users)")}
|
||||
assert columns == EXPECTED_USER_COLUMNS
|
||||
queries = [
|
||||
("SELECT COUNT(*) FROM group_log WHERE uid=? AND ts>=?", (1, 0)),
|
||||
("SELECT DISTINCT uid FROM group_log WHERE chat_id=? AND ts>?", (1, 0)),
|
||||
("DELETE FROM group_log WHERE ts<?", (0,)),
|
||||
]
|
||||
for sql, args in queries:
|
||||
plan = " ".join(row[3] for row in con.execute("EXPLAIN QUERY PLAN " + sql, args))
|
||||
assert "SEARCH group_log" in plan, plan
|
||||
assert "SCAN group_log" not in plan, plan
|
||||
|
||||
|
||||
def test_legacy_partial_columns_are_adopted_without_resetting_users_or_money(tmp_path):
|
||||
path = tmp_path / "legacy.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, username TEXT, token_name TEXT, "
|
||||
"api_key TEXT, created INTEGER, notified INTEGER DEFAULT 1, points INTEGER DEFAULT 0, "
|
||||
"banned INTEGER DEFAULT 0)")
|
||||
con.execute("INSERT INTO users VALUES(7,'fixture','fixture-token','fixture-key',1,1,900,1)")
|
||||
con.execute("CREATE TABLE fixture_money(uid INTEGER PRIMARY KEY, quota INTEGER)")
|
||||
con.execute("INSERT INTO fixture_money VALUES(7,123456)")
|
||||
bot_schema.initialize_bot_db(path)
|
||||
bot_schema.initialize_bot_db(path)
|
||||
with sqlite3.connect(path) as con:
|
||||
assert con.execute("SELECT points,banned,api_key FROM users WHERE tg_id=7").fetchone() == (900, 1, "fixture-key")
|
||||
assert con.execute("SELECT quota FROM fixture_money WHERE uid=7").fetchone()[0] == 123456
|
||||
assert con.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
|
||||
|
||||
def test_migration_failure_rolls_back_both_ddl_and_version(tmp_path, monkeypatch):
|
||||
path = tmp_path / "failure.db"
|
||||
def broken(con):
|
||||
con.execute("CREATE TABLE should_roll_back(value INTEGER)")
|
||||
raise sqlite3.OperationalError("fixture failure")
|
||||
monkeypatch.setattr(bot_schema, "_activity_indexes", broken)
|
||||
with sqlite3.connect(path) as con:
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="migration v2 failed"):
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert not con.in_transaction
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == 0
|
||||
assert not con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
||||
|
||||
|
||||
def test_future_schema_is_refused_without_downgrade_or_data_changes(tmp_path):
|
||||
path = tmp_path / "future.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("PRAGMA user_version=999")
|
||||
con.execute("CREATE TABLE keep_me(value INTEGER)")
|
||||
con.execute("INSERT INTO keep_me VALUES(12)")
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="unsupported bot schema version"):
|
||||
bot_schema.initialize_bot_db(path)
|
||||
with sqlite3.connect(path) as con:
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == 999
|
||||
assert con.execute("SELECT value FROM keep_me").fetchall() == [(12,)]
|
||||
|
||||
|
||||
def test_user_version_is_read_after_write_admission(tmp_path):
|
||||
path = tmp_path / "race.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
changed = False
|
||||
def competing_starter(statement):
|
||||
nonlocal changed
|
||||
if statement == "BEGIN IMMEDIATE" and not changed:
|
||||
changed = True
|
||||
with sqlite3.connect(path) as other:
|
||||
other.execute("PRAGMA user_version=999")
|
||||
con.set_trace_callback(competing_starter)
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="unsupported bot schema version"):
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert changed
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == 999
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["DELETE", "WAL"])
|
||||
def test_existing_journal_mode_and_foreign_key_policy_are_not_changed(tmp_path, mode):
|
||||
path = tmp_path / "journal.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("PRAGMA journal_mode=" + mode)
|
||||
con.execute("PRAGMA foreign_keys=OFF")
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert con.execute("PRAGMA journal_mode").fetchone()[0].lower() == mode.lower()
|
||||
assert con.execute("PRAGMA foreign_keys").fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_active_caller_transaction_is_refused_not_committed(tmp_path):
|
||||
with sqlite3.connect(tmp_path / "active.db") as con:
|
||||
con.execute("CREATE TABLE existing(value INTEGER)")
|
||||
con.execute("INSERT INTO existing VALUES(5)")
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="outside a transaction"):
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert con.in_transaction
|
||||
con.rollback()
|
||||
assert con.execute("SELECT * FROM existing").fetchall() == []
|
||||
|
||||
|
||||
def test_current_version_with_missing_index_is_not_silently_accepted(tmp_path):
|
||||
path = tmp_path / "drift.db"
|
||||
bot_schema.initialize_bot_db(path)
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("DROP INDEX idx_group_log_ts")
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="missing bot activity index"):
|
||||
bot_schema.initialize_bot_db(path)
|
||||
|
||||
|
||||
def test_index_name_collision_does_not_mark_migration_successful(tmp_path):
|
||||
path = tmp_path / "collision.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
bot_schema._initial_schema(con)
|
||||
con.commit()
|
||||
con.execute("CREATE INDEX idx_group_log_ts ON group_log(uid)")
|
||||
with pytest.raises(bot_schema.BotSchemaError, match="incompatible bot activity index"):
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == 0
|
||||
|
||||
|
||||
def test_initialize_prunes_only_old_group_logs_preserving_recent_records(tmp_path):
|
||||
path = tmp_path / "retention.db"
|
||||
bot_schema.initialize_bot_db(path)
|
||||
now = int(time.time())
|
||||
with sqlite3.connect(path) as con:
|
||||
con.executemany("INSERT INTO group_log(chat_id,uid,ts) VALUES(1,2,?)", [(now - 31 * 86400,), (now,)])
|
||||
bot_schema.initialize_bot_db(path)
|
||||
with sqlite3.connect(path) as con:
|
||||
assert con.execute("SELECT ts FROM group_log").fetchall() == [(now,)]
|
||||
|
||||
|
||||
def test_retention_lock_does_not_abort_startup_after_successful_migration(tmp_path, monkeypatch, caplog):
|
||||
path = tmp_path / "cleanup-lock.db"
|
||||
real_connect = sqlite3.connect
|
||||
|
||||
class RetentionLocked(sqlite3.Connection):
|
||||
def execute(self, sql, *args, **kwargs):
|
||||
if sql.startswith("DELETE FROM group_log"):
|
||||
raise sqlite3.OperationalError("fixture lock")
|
||||
return super().execute(sql, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(bot_schema.sqlite3, "connect",
|
||||
lambda *args, **kwargs: real_connect(*args, factory=RetentionLocked, **kwargs))
|
||||
bot_schema.initialize_bot_db(path)
|
||||
assert "bot log retention skipped (OperationalError)" in caplog.text
|
||||
assert "fixture lock" not in caplog.text
|
||||
with real_connect(path) as con:
|
||||
assert con.execute("PRAGMA user_version").fetchone()[0] == bot_schema.SCHEMA_VERSION
|
||||
|
||||
|
||||
def test_migration_leaves_attached_gateway_schema_and_quota_untouched(tmp_path):
|
||||
gateway = tmp_path / "gateway.db"
|
||||
with sqlite3.connect(gateway) as con:
|
||||
con.execute("CREATE TABLE users(id INTEGER PRIMARY KEY, quota INTEGER)")
|
||||
con.execute("INSERT INTO users VALUES(7,654321)")
|
||||
with sqlite3.connect(tmp_path / "bot.db") as con:
|
||||
con.execute("ATTACH DATABASE ? AS gateway", (str(gateway),))
|
||||
bot_schema.migrate_bot_schema(con)
|
||||
assert con.execute("SELECT quota FROM gateway.users WHERE id=7").fetchone()[0] == 654321
|
||||
assert con.execute("PRAGMA gateway.user_version").fetchone()[0] == 0
|
||||
assert [r[1] for r in con.execute("PRAGMA gateway.table_info(users)")] == ["id", "quota"]
|
||||
@@ -0,0 +1,370 @@
|
||||
"""Exercise actual bot gateway bodies without importing the bot or accessing live data."""
|
||||
import ast
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import random
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
import unittest
|
||||
|
||||
import aiohttp
|
||||
|
||||
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||||
sys.path.insert(0, str(BOT))
|
||||
sys.path.insert(0, str(BOT.parent / "gateway"))
|
||||
public_error = importlib.import_module("gateway_errors").public_error
|
||||
adapter = importlib.import_module("bot_stability")
|
||||
stability = importlib.import_module("request_stability")
|
||||
StabilityController, DeadlineExceeded = stability.StabilityController, stability.DeadlineExceeded
|
||||
|
||||
|
||||
class Content:
|
||||
def __init__(self, frames=(), error=None):
|
||||
self.frames, self.error = frames, error
|
||||
|
||||
async def read(self, size):
|
||||
return b'{"error":{"message":"provider rejected"}}'
|
||||
|
||||
def __aiter__(self):
|
||||
return self.iterate()
|
||||
|
||||
async def iterate(self):
|
||||
for frame in self.frames:
|
||||
yield frame
|
||||
if self.error:
|
||||
raise self.error
|
||||
|
||||
|
||||
class Response:
|
||||
def __init__(self, frames=(), status=200, error=None, body=None):
|
||||
self.content = Content(frames, error)
|
||||
self.status = status
|
||||
self.body = body or {"choices": [{"message": {"content": "unchanged output"}}]}
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, responses):
|
||||
self.responses = list(responses)
|
||||
self.calls = []
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
self.calls.append((url, kwargs))
|
||||
result = self.responses.pop(0)
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
return result
|
||||
|
||||
|
||||
def frame(content=None, *, finish=None, error=False):
|
||||
body = ({"error": {"message": "sensitive provider detail"}} if error else
|
||||
{"choices": [{"delta": {"content": content}, "finish_reason": finish}]})
|
||||
return ("data: " + json.dumps(body) + "\n\n").encode()
|
||||
|
||||
|
||||
def actual_gateway(session, controller=None):
|
||||
"""Only the named definitions are executed; all module-level effects are excluded."""
|
||||
filename = BOT / "grok_bot.py"
|
||||
if not filename.exists():
|
||||
filename = BOT / "iishko_bot.py"
|
||||
tree = ast.parse(filename.read_text(encoding="utf-8"))
|
||||
wanted = {"gw_chat_stream", "gw_call", "_gw_call_once", "gw_chat", "gw_chat_tools"}
|
||||
definitions: list[ast.stmt] = [
|
||||
n for n in tree.body
|
||||
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
|
||||
and n.name in wanted | {"_gw_policy_error", "_sampling"}
|
||||
]
|
||||
assert wanted.issubset({n.name for n in definitions})
|
||||
|
||||
@asynccontextmanager
|
||||
async def session_ctx():
|
||||
yield session
|
||||
|
||||
async def response_json(response):
|
||||
return response.body
|
||||
|
||||
class EmptyChatResponse(RuntimeError):
|
||||
pass
|
||||
|
||||
class ModelIdentityError(RuntimeError):
|
||||
pass
|
||||
|
||||
namespace = {
|
||||
"asyncio": asyncio, "aiohttp": aiohttp, "time": time, "random": random,
|
||||
"log": logging.getLogger("gateway-test"), "_STREAM_TOTAL": 360,
|
||||
"_STREAM_SOCK_READ": 120, "_SEND_GAP": 0, "GW_BASE": "http://billing.invalid/v1",
|
||||
"GW_KEY": "test-only-placeholder", "BOT_TOOLS": [], "SAMPLING_REJECTED_MODELS": set(),
|
||||
"_alias": lambda model: model, "_thinking_off": lambda model: {},
|
||||
"_brand_scrub": lambda text: text, "_PARTIAL_MARK": " [partial]",
|
||||
"_GW_PROV_DEAD": (), "_GW_CHANNEL_DEAD": (), "_GW_USER_QUOTA": (),
|
||||
"_QUOTA429_MARKERS": (), "_POLICY_MARKERS": (), "_POLICY_USERMSG": "rejected",
|
||||
"_pm_class": lambda model: False, "_effort_mt": lambda: 100,
|
||||
"CHAT_FALLBACK": [], "check_response_model": lambda *args: None,
|
||||
"_gw_session_ctx": session_ctx, "_json": response_json,
|
||||
"PartialReply": adapter.PartialReply,
|
||||
"EmptyChatResponse": EmptyChatResponse, "ModelIdentityError": ModelIdentityError,
|
||||
"generation_error": adapter.generation_error, "BOT_DB": "unused.db",
|
||||
"DeadlineExceeded": DeadlineExceeded,
|
||||
"public_error": public_error,
|
||||
}
|
||||
exec(compile(ast.Module(body=definitions, type_ignores=[]), str(filename), "exec"), namespace)
|
||||
gate = adapter.BotStability(namespace, controller=controller)
|
||||
namespace["_STABILITY_GATE"] = gate
|
||||
gate.install_wrappers()
|
||||
return namespace, gate
|
||||
|
||||
|
||||
class GatewayContracts(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_success_payload_and_return_are_unchanged(self):
|
||||
text = "Exact output / original <symbols> 日本語"
|
||||
session = Session([Response([frame(text), frame(finish="stop"), b"data: [DONE]\n\n"])])
|
||||
ns, gate = actual_gateway(session)
|
||||
sent = []
|
||||
async def send(text): sent.append(text)
|
||||
result = await ns["gw_chat_stream"]([{"role": "user", "content": "unchanged input"}], "model-x", send)
|
||||
self.assertEqual(result, text)
|
||||
self.assertIn(text, sent)
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
url, request = session.calls[0]
|
||||
self.assertEqual(url, "http://billing.invalid/v1/chat/completions")
|
||||
self.assertEqual(request["json"]["messages"], [{"role": "user", "content": "unchanged input"}])
|
||||
self.assertEqual(request["json"]["model"], "model-x")
|
||||
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
||||
|
||||
async def test_partial_transport_failure_is_not_replayed(self):
|
||||
session = Session([Response([frame("partial original")], error=aiohttp.ServerDisconnectedError())])
|
||||
ns, gate = actual_gateway(session)
|
||||
sent = []
|
||||
async def send(text): sent.append(text)
|
||||
result = await ns["gw_chat_stream"]([], "model-x", send)
|
||||
self.assertEqual(result, "partial original")
|
||||
self.assertTrue(result.incomplete)
|
||||
self.assertEqual(sent[-1], "partial original [partial]")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 0)
|
||||
|
||||
async def test_sse_error_after_content_is_partial_not_success(self):
|
||||
session = Session([Response([frame("paid output"), frame(error=True)])])
|
||||
ns, gate = actual_gateway(session)
|
||||
sent = []
|
||||
async def send(text): sent.append(text)
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "paid output")
|
||||
self.assertEqual(sent[-1], "paid output [partial]")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertNotIn("sensitive", str(sent))
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1)
|
||||
|
||||
async def test_ambiguous_disconnect_before_content_is_terminal(self):
|
||||
session = Session([Response(error=aiohttp.ServerDisconnectedError())])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): self.fail("must not deliver")
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
await ns["gw_chat_stream"]([], "model-x", send)
|
||||
self.assertTrue(getattr(cm.exception, "terminal", False))
|
||||
self.assertTrue(getattr(cm.exception, "ambiguous", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1)
|
||||
|
||||
async def test_non_stream_transport_timeout_is_not_replayed(self):
|
||||
session = Session([asyncio.TimeoutError()])
|
||||
ns, gate = actual_gateway(session)
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
await ns["gw_call"]("/chat/completions", {"model": "model-x"})
|
||||
self.assertTrue(getattr(cm.exception, "terminal", False))
|
||||
self.assertTrue(getattr(cm.exception, "ambiguous", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
||||
|
||||
async def test_non_stream_status_error_cannot_trigger_legacy_fallback(self):
|
||||
session = Session([Response(status=503, body={"error": {"message": "unavailable"}})])
|
||||
ns, gate = actual_gateway(session)
|
||||
with self.assertRaises(RuntimeError) as cm:
|
||||
await ns["gw_chat_tools"]([], "model-x")
|
||||
self.assertTrue(getattr(cm.exception, "terminal", False))
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1)
|
||||
|
||||
async def test_pre_content_retry_is_bounded_same_model(self):
|
||||
session = Session([Response(status=429), Response([frame("ok"), frame(finish="stop")])])
|
||||
ns, gate = actual_gateway(session)
|
||||
# Keep the real retry/sleep algorithm; a short caller deadline is tested separately.
|
||||
async def send(text): pass
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "ok")
|
||||
self.assertEqual(len(session.calls), 2)
|
||||
self.assertEqual([c[1]["json"]["model"] for c in session.calls], ["model-x", "model-x"])
|
||||
|
||||
async def test_caller_deadline_is_not_extended(self):
|
||||
session = Session([Response(status=429)])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): pass
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(DeadlineExceeded):
|
||||
await ns["gw_chat_stream"]([], "model-x", send, _deadline=started + .03)
|
||||
self.assertLess(time.monotonic() - started, .3)
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
||||
|
||||
async def test_telegram_delivery_error_does_not_penalize_model(self):
|
||||
session = Session([Response([frame("already generated"), frame(finish="stop")])])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): raise ValueError("delivery only")
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "already generated")
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 0)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 0)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["partial"], 1)
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
|
||||
async def test_eof_without_finish_is_partial_failure(self):
|
||||
session = Session([Response([frame("unfinished")])])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): pass
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "model-x", send), "unfinished")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["dependency_failure"], 1)
|
||||
|
||||
|
||||
class AdapterContracts(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_nested_calls_share_lease_and_budget(self):
|
||||
controller = StabilityController(global_limit=1, model_limit=1)
|
||||
ns: dict[str, Any] = {"BOT_DB": "unused.db"}
|
||||
async def gw_call(path, payload, t=180):
|
||||
self.assertEqual(controller.snapshot()["active"], 1)
|
||||
self.assertLess(t, .08)
|
||||
return {"unchanged": True}
|
||||
async def gw_chat(messages, model):
|
||||
await asyncio.sleep(.02)
|
||||
return await ns["gw_call"]("/chat/completions", {"model": model})
|
||||
ns.update(gw_call=gw_call, gw_chat=gw_chat)
|
||||
gate = adapter.BotStability(ns, controller=controller)
|
||||
gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 2, .08))
|
||||
try:
|
||||
self.assertEqual(await ns["gw_chat"]([], "model-x"), {"unchanged": True})
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
self.assertEqual(controller.snapshot()["outcomes"]["success"], 1)
|
||||
self.assertEqual(controller.snapshot()["active"], 0)
|
||||
|
||||
async def test_rejected_queue_does_not_spend_premium_cap(self):
|
||||
controller = StabilityController(global_limit=1, model_limit=1, queue_limit=1)
|
||||
hold, started = asyncio.Event(), asyncio.Event()
|
||||
async def occupy():
|
||||
started.set(); await hold.wait()
|
||||
active = asyncio.create_task(controller.run("busy", occupy, user_id=1))
|
||||
await started.wait()
|
||||
cap_calls = []
|
||||
async def gw_chat_stream(messages, model, send, t=360, _deadline=None):
|
||||
self.fail("expired queued request must never send")
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": gw_chat_stream,
|
||||
"pm_cap_take": lambda *args: cap_calls.append(args) or (True, 1, 10)}
|
||||
gate = adapter.BotStability(ns, controller=controller); gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(9, 0, .02))
|
||||
try:
|
||||
with self.assertRaises(DeadlineExceeded):
|
||||
await ns["gw_chat_stream"]([], "busy", None)
|
||||
finally:
|
||||
adapter.POLICY.reset(token); hold.set(); await active
|
||||
self.assertEqual(cap_calls, [])
|
||||
self.assertEqual(controller.snapshot()["active"], 0)
|
||||
|
||||
async def test_admitted_stream_spends_cap_once(self):
|
||||
calls = []
|
||||
ns = {"BOT_DB": "unused.db", "pm_cap_take": lambda *args: calls.append(args) or (True, 1, 10)}
|
||||
async def gw_chat_stream(messages, model, send, t=360, _deadline=None):
|
||||
if not messages:
|
||||
return await ns["gw_chat_stream"](["tool round"], model, send, _deadline=_deadline)
|
||||
return "exact"
|
||||
ns["gw_chat_stream"] = gw_chat_stream
|
||||
gate = adapter.BotStability(ns); gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 1, 60))
|
||||
try:
|
||||
self.assertEqual(await ns["gw_chat_stream"]([], "model-x", None), "exact")
|
||||
finally: adapter.POLICY.reset(token)
|
||||
self.assertEqual(calls, [(7, "model-x")])
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
|
||||
|
||||
async def test_child_task_inherits_policy_not_lease(self):
|
||||
ns: dict[str, Any] = {"BOT_DB": "unused.db"}
|
||||
gate = adapter.BotStability(ns)
|
||||
class Preferences:
|
||||
def get(self, uid): return 360
|
||||
gate.preferences = Preferences(); ns["tier_of"] = lambda uid: 4
|
||||
child_result = []
|
||||
async def handler(event, data):
|
||||
async def child(): child_result.append(adapter.POLICY.get())
|
||||
await asyncio.create_task(child())
|
||||
await gate.middleware(handler, SimpleNamespace(from_user=SimpleNamespace(id=7)), {})
|
||||
self.assertEqual(child_result, [adapter.RequestPolicy(7, 3, 360)])
|
||||
self.assertEqual(adapter.POLICY.get(), adapter.RequestPolicy())
|
||||
|
||||
async def test_non_generation_call_is_not_queued(self):
|
||||
ns: dict[str, Any] = {"BOT_DB": "unused.db"}
|
||||
async def gw_call(path, payload, t=180): return payload
|
||||
ns["gw_call"] = gw_call
|
||||
gate = adapter.BotStability(ns); gate.install_wrappers()
|
||||
payload = {"model": "media-x", "original": True}
|
||||
self.assertIs(await ns["gw_call"]("/images/generations", payload), payload)
|
||||
self.assertEqual(gate.controller.snapshot()["model_count"], 0)
|
||||
|
||||
async def test_real_router_registration_and_wait_callback(self):
|
||||
from aiogram import Router
|
||||
router = Router()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
gate = adapter.BotStability({"BOT_DB": str(Path(tmp)/"bot.db"), "tier_of": lambda uid: 3})
|
||||
gate.register(router)
|
||||
self.assertEqual(len(router.message.handlers), 1)
|
||||
self.assertEqual(len(router.callback_query.handlers), 1)
|
||||
sent = []
|
||||
class Message:
|
||||
from_user = SimpleNamespace(id=7)
|
||||
chat = SimpleNamespace(type="private")
|
||||
async def answer(self, text, **kwargs): sent.append((text, kwargs))
|
||||
async def edit_text(self, text, **kwargs): sent.append((text, kwargs))
|
||||
class Query:
|
||||
from_user = SimpleNamespace(id=7)
|
||||
message = Message()
|
||||
data = "stability_wait:360"
|
||||
async def answer(self, text, **kwargs): pass
|
||||
await router.message.handlers[0].callback(Message())
|
||||
self.assertIn("180 с", sent[-1][0])
|
||||
await router.callback_query.handlers[0].callback(Query())
|
||||
self.assertEqual(gate.preferences.get(7), 360)
|
||||
self.assertIn("360 с", sent[-1][0])
|
||||
self.assertTrue(all(len(b.callback_data.encode()) < 64 for b in sent[-1][1]["reply_markup"].inline_keyboard[0]))
|
||||
|
||||
|
||||
class PreferenceContracts(unittest.TestCase):
|
||||
def test_preferences_persist_without_touching_bot_db(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp)/"preferences.db"
|
||||
prefs = adapter.WaitPreferences(path)
|
||||
self.assertEqual(prefs.get(7), 180)
|
||||
self.assertFalse(path.exists())
|
||||
prefs.set(7, 60)
|
||||
self.assertEqual(adapter.WaitPreferences(path).get(7), 60)
|
||||
for invalid in (True, 0, 61, 720):
|
||||
with self.assertRaises(ValueError): prefs.set(7, invalid)
|
||||
self.assertEqual(prefs.get(7), 60)
|
||||
|
||||
def test_error_markers_are_explicit_and_do_not_trust_text(self):
|
||||
for status in (None, 429, 500, 502, 503, 504):
|
||||
self.assertTrue(adapter.generation_error("message", status=status).stability_dependency_failure)
|
||||
for status in (400, 401, 402, 403, 404):
|
||||
self.assertFalse(adapter.generation_error("timeout, unavailable", status=status).stability_dependency_failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,374 @@
|
||||
"""Regression contracts for final stability review findings; all I/O stays local."""
|
||||
import ast
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from test_bot_stability import (BOT, Content, Response, Session, actual_gateway,
|
||||
adapter, frame, stability)
|
||||
|
||||
|
||||
class StreamEdges(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_default_model_is_admitted_not_bypassed(self):
|
||||
session = Session([Response()])
|
||||
ns, gate = actual_gateway(session)
|
||||
self.assertEqual(await ns["gw_chat"]([]), "unchanged output")
|
||||
self.assertEqual(session.calls[0][1]["json"]["model"], "grok-4.7")
|
||||
self.assertEqual(gate.controller.snapshot()["model_count"], 1)
|
||||
|
||||
async def test_final_done_without_newline_is_complete(self):
|
||||
session = Session([Response([frame("exact"), b"data: [DONE]"])])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): pass
|
||||
reply = await ns["gw_chat_stream"]([], "m", send)
|
||||
self.assertEqual(reply, "exact")
|
||||
self.assertNotIsInstance(reply, adapter.PartialReply)
|
||||
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
|
||||
self.assertEqual(gate.controller.snapshot()["models"]["m"]["circuit"], "closed")
|
||||
|
||||
async def test_delivery_transport_error_is_not_upstream_failure(self):
|
||||
for exception in (TimeoutError("Telegram timeout"), ConnectionResetError("Telegram reset")):
|
||||
with self.subTest(error=type(exception).__name__):
|
||||
session = Session([Response([frame("already paid"), frame(finish="stop")])])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): raise exception
|
||||
reply = await ns["gw_chat_stream"]([], "m", send)
|
||||
self.assertEqual(reply, "already paid")
|
||||
self.assertTrue(reply.incomplete)
|
||||
state = gate.controller.snapshot()
|
||||
self.assertEqual(state["outcomes"]["partial"], 1)
|
||||
self.assertEqual(state["outcomes"]["dependency_failure"], 0)
|
||||
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
|
||||
async def test_deadline_keeps_already_delivered_partial_without_model_penalty(self):
|
||||
sent = []
|
||||
class SlowContent(Content):
|
||||
async def iterate(self):
|
||||
yield frame("delivered unchanged")
|
||||
await asyncio.Event().wait()
|
||||
response = Response()
|
||||
response.content = SlowContent()
|
||||
session = Session([response])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): sent.append(text)
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .03))
|
||||
try:
|
||||
reply = await ns["gw_chat_stream"]([], "m", send)
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
self.assertEqual(reply, "delivered unchanged")
|
||||
self.assertTrue(reply.incomplete)
|
||||
self.assertEqual(sent[0], "delivered unchanged")
|
||||
state = gate.controller.snapshot()
|
||||
self.assertEqual(state["active"], 0)
|
||||
self.assertEqual(state["outcomes"]["partial"], 1)
|
||||
self.assertEqual(state["outcomes"]["success"], 0)
|
||||
self.assertEqual(state["models"]["m"]["limit"], 4)
|
||||
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
|
||||
async def test_user_cancel_after_partial_propagates_and_frees_permit(self):
|
||||
delivered = asyncio.Event()
|
||||
class SlowContent(Content):
|
||||
async def iterate(self):
|
||||
yield frame("partial")
|
||||
await asyncio.Event().wait()
|
||||
response = Response()
|
||||
response.content = SlowContent()
|
||||
session = Session([response])
|
||||
ns, gate = actual_gateway(session)
|
||||
async def send(text): delivered.set()
|
||||
task = asyncio.create_task(ns["gw_chat_stream"]([], "m", send))
|
||||
await asyncio.wait_for(delivered.wait(), 2)
|
||||
task.cancel()
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await task
|
||||
state = gate.controller.snapshot()
|
||||
self.assertEqual(state["active"], 0)
|
||||
self.assertEqual(state["queued"], 0)
|
||||
self.assertEqual(state["outcomes"]["cancelled"], 1)
|
||||
self.assertEqual(state["models"]["m"]["circuit"], "closed")
|
||||
self.assertEqual(len(session.calls), 1)
|
||||
|
||||
async def test_final_render_keeps_marker_after_cleaning_for_both_handlers(self):
|
||||
path = BOT / "grok_bot.py"
|
||||
if not path.exists(): path = BOT / "iishko_bot.py"
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
found = 0
|
||||
for fn in ast.walk(tree):
|
||||
if not isinstance(fn, ast.AsyncFunctionDef): continue
|
||||
flags: list[ast.stmt] = [n for n in fn.body if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "_partial" for t in n.targets)]
|
||||
renders: list[ast.stmt] = [n for n in fn.body if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "_ch" for t in n.targets)
|
||||
and "_PARTIAL_MARK" in ast.unparse(n)]
|
||||
if not flags or not renders: continue
|
||||
namespace = {"reply": adapter.PartialReply("raw"), "PartialReply": adapter.PartialReply,
|
||||
"_PARTIAL_MARK": " [incomplete]", "_chunks_html": lambda text: [text]}
|
||||
exec(compile(ast.Module(body=flags, type_ignores=[]), str(path), "exec"), namespace)
|
||||
namespace["_r"] = str(namespace["reply"])
|
||||
exec(compile(ast.Module(body=renders, type_ignores=[]), str(path), "exec"), namespace)
|
||||
self.assertEqual(namespace["_ch"], ["raw [incomplete]"])
|
||||
found += 1
|
||||
self.assertEqual(found, 2)
|
||||
|
||||
|
||||
class AdapterEdges(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_inline_dispatcher_resolves_owner_and_rank(self):
|
||||
from aiogram import Bot, Dispatcher, Router
|
||||
from aiogram.types import Update, InlineQuery, User
|
||||
class Preferences:
|
||||
def get(self, uid): return 60
|
||||
calls = []
|
||||
gate = adapter.BotStability({"BOT_DB": "unused.db", "tier_of": lambda uid: 4},
|
||||
preferences=Preferences())
|
||||
router = Router()
|
||||
gate.register(router)
|
||||
async def handle(query): calls.append(adapter.POLICY.get())
|
||||
router.inline_query.register(handle)
|
||||
dispatcher = Dispatcher()
|
||||
dispatcher.include_router(router)
|
||||
bot = Bot("123456:test-only-placeholder")
|
||||
try:
|
||||
await dispatcher.feed_update(bot, Update(update_id=1, inline_query=InlineQuery(
|
||||
id="test", from_user=User(id=7, is_bot=False, first_name="Test"), query="x", offset="")))
|
||||
finally:
|
||||
await bot.session.close()
|
||||
self.assertEqual(calls, [adapter.RequestPolicy(7, 3, 60)])
|
||||
self.assertEqual(adapter.POLICY.get(), adapter.RequestPolicy())
|
||||
|
||||
async def test_rank_cache_is_bounded_and_does_not_cache_access_authority(self):
|
||||
calls = []
|
||||
class Preferences:
|
||||
def get(self, uid): return 180
|
||||
gate = adapter.BotStability({"BOT_DB": "unused.db", "tier_of": lambda uid: calls.append(uid) or 3},
|
||||
preferences=Preferences())
|
||||
self.assertEqual(gate.policy_for(7).priority, 2)
|
||||
self.assertEqual(gate.policy_for(7).priority, 2)
|
||||
self.assertEqual(calls, [7])
|
||||
for uid in range(4100): gate.policy_for(uid)
|
||||
self.assertLessEqual(len(gate._rank_cache), 4096)
|
||||
|
||||
async def test_cap_cancel_or_deadline_refunds_exactly_once_without_dispatch(self):
|
||||
for timed_out in (False, True):
|
||||
with self.subTest(timed_out=timed_out):
|
||||
ready, release = threading.Event(), threading.Event()
|
||||
ledger = {"used": 0, "refunds": 0, "dispatch": 0}
|
||||
def reserve(uid, model):
|
||||
ledger["used"] += 1
|
||||
ready.set()
|
||||
if not release.wait(2): raise RuntimeError("test did not release worker")
|
||||
return True, 1, 10, "old-day-receipt"
|
||||
def refund(receipt):
|
||||
self.assertEqual(receipt, "old-day-receipt")
|
||||
ledger["used"] -= 1
|
||||
ledger["refunds"] += 1
|
||||
async def gw_chat_stream(messages, model, send, t=360, _deadline=None):
|
||||
ledger["dispatch"] += 1
|
||||
return "must not send"
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": gw_chat_stream,
|
||||
"pm_cap_reserve": reserve, "pm_cap_release": refund}
|
||||
gate = adapter.BotStability(ns); gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .04 if timed_out else 60))
|
||||
try:
|
||||
task = asyncio.create_task(ns["gw_chat_stream"]([], "m", None))
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
try:
|
||||
self.assertTrue(await asyncio.to_thread(ready.wait, 1))
|
||||
if not timed_out: task.cancel()
|
||||
with self.assertRaises(stability.DeadlineExceeded if timed_out else asyncio.CancelledError):
|
||||
await task
|
||||
self.assertEqual(ledger["dispatch"], 0)
|
||||
finally:
|
||||
release.set()
|
||||
if gate._cleanup_tasks:
|
||||
await asyncio.wait_for(asyncio.gather(*gate._cleanup_tasks), 3)
|
||||
self.assertEqual(ledger, {"used": 0, "refunds": 1, "dispatch": 0})
|
||||
self.assertEqual(gate.controller.snapshot()["active"], 0)
|
||||
self.assertEqual(gate.controller.snapshot()["models"]["m"]["circuit"], "closed")
|
||||
|
||||
async def test_cancelled_cap_workers_cannot_build_unbounded_backlog(self):
|
||||
ready, release = threading.Event(), threading.Event()
|
||||
reservations = []
|
||||
def reserve(uid, model):
|
||||
reservations.append(uid)
|
||||
ready.set()
|
||||
if not release.wait(2):
|
||||
raise RuntimeError("test did not release worker")
|
||||
return True, 1, 10, "receipt"
|
||||
async def stream(messages, model, send, t=360, _deadline=None):
|
||||
self.fail("must not dispatch")
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream,
|
||||
"pm_cap_reserve": reserve, "pm_cap_release": lambda key: None}
|
||||
controller = stability.StabilityController(global_limit=1)
|
||||
gate = adapter.BotStability(ns, controller=controller)
|
||||
gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7))
|
||||
try:
|
||||
first = asyncio.create_task(ns["gw_chat_stream"]([], "m", None))
|
||||
self.assertTrue(await asyncio.to_thread(ready.wait, 1))
|
||||
first.cancel()
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await first
|
||||
with self.assertRaises(stability.QueueFull):
|
||||
await ns["gw_chat_stream"]([], "m", None)
|
||||
self.assertEqual(reservations, [7])
|
||||
self.assertEqual(len(gate._cap_pending), 1)
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
release.set()
|
||||
if gate._cleanup_tasks:
|
||||
await asyncio.wait_for(asyncio.gather(*gate._cleanup_tasks), 3)
|
||||
self.assertFalse(gate._cap_pending)
|
||||
|
||||
async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self):
|
||||
calls = []
|
||||
def reserve(uid, model):
|
||||
time.sleep(.02)
|
||||
return True, 1, 10, "receipt"
|
||||
async def stream(messages, model, send, t=360, _deadline=None):
|
||||
calls.append(t)
|
||||
self.assertLess(t, .07)
|
||||
self.assertGreater(t, 0)
|
||||
return "exact"
|
||||
ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream, "pm_cap_reserve": reserve,
|
||||
"pm_cap_release": lambda key: self.fail("dispatched request must retain its unit")}
|
||||
gate = adapter.BotStability(ns); gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .08))
|
||||
try: self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
|
||||
finally: adapter.POLICY.reset(token)
|
||||
self.assertEqual(len(calls), 1)
|
||||
self.assertFalse(gate._cleanup_tasks)
|
||||
|
||||
async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self):
|
||||
calls = []
|
||||
async def gw_call(path, payload, t=180):
|
||||
calls.append(t)
|
||||
return "exact"
|
||||
ns = {"BOT_DB": "unused.db", "gw_call": gw_call}
|
||||
gate = adapter.BotStability(ns)
|
||||
gate.install_wrappers()
|
||||
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, 360))
|
||||
try:
|
||||
result = await ns["gw_call"]("/chat/completions", {"model": "m"}, t=.05)
|
||||
finally:
|
||||
adapter.POLICY.reset(token)
|
||||
self.assertEqual(result, "exact")
|
||||
self.assertEqual(calls, [.05])
|
||||
|
||||
async def test_other_task_can_free_the_last_user_slot_for_nested_model(self):
|
||||
controller = stability.StabilityController(global_limit=3, user_limit=2)
|
||||
ready, release = asyncio.Event(), asyncio.Event()
|
||||
async def holder():
|
||||
ready.set()
|
||||
await release.wait()
|
||||
background = asyncio.create_task(controller.run("background", holder, user_id=7))
|
||||
await asyncio.wait_for(ready.wait(), 1)
|
||||
async def inner():
|
||||
return "inner"
|
||||
async def outer():
|
||||
asyncio.get_running_loop().call_later(.01, release.set)
|
||||
return await controller.run("other", inner, user_id=7)
|
||||
try:
|
||||
self.assertEqual(await controller.run("outer", outer, user_id=7), "inner")
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.wait_for(background, 1)
|
||||
self.assertEqual(controller.snapshot()["active"], 0)
|
||||
self.assertEqual(controller.snapshot()["queued"], 0)
|
||||
|
||||
async def test_same_task_other_model_rejects_self_deadlock_without_bypassing_user_limit(self):
|
||||
controller = stability.StabilityController(global_limit=2, user_limit=1)
|
||||
called = []
|
||||
async def inner(): called.append(True)
|
||||
async def outer():
|
||||
with self.assertRaises(stability.QueueFull):
|
||||
await controller.run("other", inner, user_id=7)
|
||||
return "ok"
|
||||
self.assertEqual(await controller.run("m", outer, user_id=7), "ok")
|
||||
self.assertEqual(called, [])
|
||||
self.assertEqual(controller.snapshot()["active"], 0)
|
||||
self.assertEqual(controller.snapshot()["queued"], 0)
|
||||
|
||||
|
||||
class PremiumReceiptStore(unittest.TestCase):
|
||||
def test_actual_cap_transaction_and_midnight_refund(self):
|
||||
path = BOT / "grok_bot.py"
|
||||
if not path.exists(): path = BOT / "iishko_bot.py"
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
wanted = {"pm_cap_take", "pm_cap_reserve", "pm_cap_release"}
|
||||
definitions: list[ast.stmt] = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in wanted]
|
||||
self.assertEqual({n.name for n in definitions if isinstance(n, ast.FunctionDef)}, wanted)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = Path(tmp) / "bot.db"
|
||||
namespace = {"sqlite3": sqlite3, "BOT_DB": str(db), "_pm_class": lambda model: "premium",
|
||||
"PM_DAY_CAPS": {"premium": {1: 2}}, "earned_rank": lambda uid: 1,
|
||||
"today_msk": lambda: "old-day"}
|
||||
exec(compile(ast.Module(body=definitions, type_ignores=[]), str(path), "exec"), namespace)
|
||||
with ThreadPoolExecutor(max_workers=3) as workers:
|
||||
receipts = list(workers.map(lambda _: namespace["pm_cap_reserve"](7, "m"), range(3)))
|
||||
self.assertEqual(sum(bool(r[0]) for r in receipts), 2)
|
||||
namespace["today_msk"] = lambda: "new-day"
|
||||
for receipt in receipts:
|
||||
if receipt[0]: namespace["pm_cap_release"](receipt[3])
|
||||
con = sqlite3.connect(db)
|
||||
try:
|
||||
self.assertEqual(con.execute("SELECT v FROM kv WHERE k='pmc:7:premium:old-day'").fetchone()[0], "0")
|
||||
self.assertEqual(con.execute("SELECT COUNT(*) FROM kv").fetchone()[0], 1)
|
||||
finally: con.close()
|
||||
self.assertEqual(namespace["pm_cap_take"](7, "m"), (True, 1, 2))
|
||||
|
||||
def test_cap_reserve_and_refund_survive_brief_real_writer_contention(self):
|
||||
path = BOT / "grok_bot.py"
|
||||
if not path.exists():
|
||||
path = BOT / "iishko_bot.py"
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
wanted = {"pm_cap_take", "pm_cap_reserve", "pm_cap_release"}
|
||||
definitions = [node for node in tree.body
|
||||
if isinstance(node, ast.FunctionDef) and node.name in wanted]
|
||||
self.assertEqual({node.name for node in definitions}, wanted)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = Path(tmp) / "bot.db"
|
||||
namespace = {"sqlite3": sqlite3, "BOT_DB": str(db),
|
||||
"_pm_class": lambda model: "premium",
|
||||
"PM_DAY_CAPS": {"premium": {1: 2}},
|
||||
"earned_rank": lambda uid: 1, "today_msk": lambda: "same-day"}
|
||||
exec(compile(ast.Module(body=definitions, type_ignores=[]), str(path), "exec"), namespace)
|
||||
blocker = sqlite3.connect(db)
|
||||
try:
|
||||
blocker.execute("CREATE TABLE kv(k TEXT PRIMARY KEY, v TEXT)")
|
||||
blocker.commit()
|
||||
with ThreadPoolExecutor(max_workers=1) as workers:
|
||||
for action in ("reserve", "release"):
|
||||
with self.subTest(action=action):
|
||||
blocker.execute("BEGIN IMMEDIATE")
|
||||
started = threading.Event()
|
||||
def run():
|
||||
started.set()
|
||||
if action == "reserve":
|
||||
return namespace["pm_cap_reserve"](7, "m")
|
||||
return namespace["pm_cap_release"]("pmc:7:premium:same-day")
|
||||
pending = workers.submit(run)
|
||||
try:
|
||||
self.assertTrue(started.wait(1))
|
||||
time.sleep(.3)
|
||||
self.assertFalse(pending.done())
|
||||
finally:
|
||||
blocker.rollback()
|
||||
result = pending.result(timeout=3)
|
||||
if action == "reserve":
|
||||
self.assertEqual(result, (True, 1, 2, "pmc:7:premium:same-day"))
|
||||
self.assertEqual(blocker.execute("SELECT v FROM kv").fetchone()[0], "0")
|
||||
finally:
|
||||
blocker.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,222 @@
|
||||
import ast
|
||||
import html
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
BOT = Path(__file__).resolve().parents[1] / "bot" / "grok_bot.py"
|
||||
|
||||
|
||||
def _tree():
|
||||
return ast.parse(BOT.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _find(tree, name):
|
||||
for node in tree.body:
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Assign)):
|
||||
if isinstance(node, ast.Assign):
|
||||
targets = [t.id for t in node.targets if isinstance(t, ast.Name)]
|
||||
if name in targets:
|
||||
return node
|
||||
elif node.name == name:
|
||||
return node
|
||||
raise AssertionError(f"{name} не найден в bot/grok_bot.py")
|
||||
|
||||
|
||||
def _source(name):
|
||||
tree = _tree()
|
||||
return ast.get_source_segment(BOT.read_text(encoding="utf-8"), _find(tree, name))
|
||||
|
||||
|
||||
def _exec(name, ns):
|
||||
src = _source(name)
|
||||
exec(compile(src, str(BOT), "exec"), ns)
|
||||
return ns[name]
|
||||
|
||||
|
||||
class _Router:
|
||||
def message(self, *a, **k):
|
||||
return lambda fn: fn
|
||||
|
||||
|
||||
class _User:
|
||||
def __init__(self, uid):
|
||||
self.id = uid
|
||||
|
||||
|
||||
class _Message:
|
||||
def __init__(self, uid):
|
||||
self.from_user = _User(uid)
|
||||
self.replies = []
|
||||
|
||||
async def answer(self, text, **kwargs):
|
||||
self.replies.append(text)
|
||||
|
||||
|
||||
def _gate(snapshot):
|
||||
return SimpleNamespace(controller=SimpleNamespace(snapshot=snapshot))
|
||||
|
||||
|
||||
def _run_queue(uid, admins, is_admin, gate, sqlite3=None):
|
||||
ns = {
|
||||
"router": _Router(),
|
||||
"Command": lambda *a, **k: object(),
|
||||
"Message": _Message,
|
||||
"ParseMode": SimpleNamespace(HTML="HTML"),
|
||||
"html": html,
|
||||
"ADMIN_IDS": set(admins),
|
||||
"is_admin": is_admin,
|
||||
"_STABILITY_GATE": gate,
|
||||
}
|
||||
if sqlite3 is not None:
|
||||
ns["sqlite3"] = sqlite3
|
||||
handler = _exec("cmd_queue", ns)
|
||||
msg = _Message(uid)
|
||||
|
||||
import asyncio
|
||||
|
||||
asyncio.run(handler(msg))
|
||||
return msg.replies
|
||||
|
||||
|
||||
def test_queue_denies_non_admin_without_touching_metrics():
|
||||
def boom():
|
||||
raise AssertionError("снапшот контроллера не должен читаться для не-админа")
|
||||
|
||||
replies = _run_queue(42, admins={1}, is_admin=lambda uid: False, gate=_gate(boom))
|
||||
assert len(replies) == 1
|
||||
assert "⛔" in replies[0]
|
||||
assert "в работе" not in replies[0]
|
||||
|
||||
|
||||
def test_queue_admin_gets_controller_metrics_only():
|
||||
snap = {
|
||||
"active": 2,
|
||||
"queued": 7,
|
||||
"limits": {"queue": 64, "user_queue": 2, "model": 8, "models": 3},
|
||||
"outcomes": {"success": 10, "partial": 1},
|
||||
"rejects": {"queue_full": 2},
|
||||
"queue_p95_seconds": 4.5,
|
||||
"models": {
|
||||
"kimi/kimi-k3.1-pro": {"active": 1, "queued": 5, "limit": 8, "circuit": "closed"},
|
||||
"claude-opus-5.5": {"active": 1, "queued": 2, "limit": 8, "circuit": "open",
|
||||
"retry_after_seconds": 12.0},
|
||||
},
|
||||
}
|
||||
replies = _run_queue(1, admins={1}, is_admin=lambda uid: False, gate=_gate(lambda: snap))
|
||||
assert len(replies) == 1
|
||||
text = replies[0]
|
||||
assert "в работе" in text and "<b>2</b>" in text and "<b>7</b>" in text
|
||||
assert "kimi/kimi-k3.1-pro" in text and "claude-opus-5.5" in text
|
||||
assert "circuit open" in text and "12с" in text
|
||||
assert "queue_full" in text and "p95" in text
|
||||
for hostile in ("RAM", "/proc", "one-api", "uptime хоста"):
|
||||
assert hostile not in text
|
||||
|
||||
|
||||
def test_queue_never_opens_host_or_upstream_db():
|
||||
class _Trap:
|
||||
def connect(self, *a, **k):
|
||||
raise AssertionError("обработчик /queue не должен открывать БД")
|
||||
|
||||
snap = {"active": 0, "queued": 0, "limits": {}, "models": {}}
|
||||
replies = _run_queue(1, admins={1}, is_admin=lambda uid: False,
|
||||
gate=_gate(lambda: snap), sqlite3=_Trap())
|
||||
assert len(replies) == 1 and "Очередь пуста" in replies[0]
|
||||
src = _source("cmd_queue")
|
||||
for forbidden in ("psutil", "/proc/", "one-api", "if True", "sqlite3", "virtual_memory"):
|
||||
assert forbidden not in src, forbidden
|
||||
|
||||
|
||||
def test_keys_notice_points_to_miniapp_and_names_subscription_gate():
|
||||
ns = {"key_notifications": SimpleNamespace(policy_summary=lambda wait, lang: ""),
|
||||
"KEY_WAIT_SEC": 0}
|
||||
notice_fn = _exec("keys_mini_notice", ns)
|
||||
for lang, marker in (("ru", "подписка на @alstack"), ("en", "subscription to @alstack")):
|
||||
text = notice_fn(lang)
|
||||
assert "Mini App" in text and marker in text
|
||||
assert "Ключи" in text or "Keys" in text
|
||||
|
||||
|
||||
def _lang():
|
||||
ns = {}
|
||||
exec(compile(_source("LANG"), str(BOT), "exec"), ns)
|
||||
return ns["LANG"]
|
||||
|
||||
|
||||
def test_lang_copy_has_no_hardcoded_model_counts():
|
||||
lang = _lang()
|
||||
for code in ("ru", "en"):
|
||||
line = lang[code]["models_line"]
|
||||
assert not re.search(r"\b\d{1,2}\b", line), (code, line)
|
||||
|
||||
|
||||
def test_lang_english_copy_has_no_cyrillic():
|
||||
lang = _lang()
|
||||
for key in ("models_line", "key_line", "gift_line"):
|
||||
value = lang["en"][key]
|
||||
assert not re.search(r"[\u0400-\u04FF]", value), (key, value)
|
||||
|
||||
|
||||
def test_queue_renders_actual_controller_snapshot_including_zero_wait():
|
||||
import asyncio
|
||||
from request_stability import StabilityController
|
||||
|
||||
async def collect():
|
||||
controller = StabilityController()
|
||||
await controller.run("glm-5.3", lambda: asyncio.sleep(0))
|
||||
return controller.snapshot()
|
||||
|
||||
snapshot = asyncio.run(collect())
|
||||
text = _run_queue(1, {1}, lambda uid: False, _gate(lambda: snapshot))[0]
|
||||
assert "p95 ожидания: 0.0 с" in text
|
||||
assert "success 1" in text
|
||||
assert "Очередь пуста" in text
|
||||
decorators = _find(_tree(), "cmd_queue").decorator_list
|
||||
assert len(decorators) == 1
|
||||
|
||||
|
||||
def test_rank_help_and_rank_stats_describe_cumulative_access_not_availability():
|
||||
import asyncio
|
||||
|
||||
ns = {}
|
||||
help_text = _exec("PROJECT_HELP_KB", ns)
|
||||
assert "ранг N открывает модели рангов 1…N" in help_text
|
||||
assert "не гарантирует работоспособность" in help_text
|
||||
assert "а не на каталог" not in help_text
|
||||
pages = []
|
||||
|
||||
async def show_page(*args):
|
||||
pages.append(args[2])
|
||||
|
||||
async def acknowledge():
|
||||
pass
|
||||
|
||||
ns.update({
|
||||
"CallbackQuery": SimpleNamespace, "asyncio": asyncio,
|
||||
"db_get": lambda uid: {"lang": "ru"},
|
||||
"compute_rank_stats": lambda: ({1: 1}, 1),
|
||||
"BADGES": _exec("BADGES", {}),
|
||||
"rank_rules_line": lambda level: str(level),
|
||||
"tge": lambda emoji: emoji, "back_row": lambda lang: "",
|
||||
"page_html": lambda lang, body, rows: body, "rich_page_s": show_page,
|
||||
})
|
||||
callback = SimpleNamespace(answer=acknowledge, from_user=_User(42),
|
||||
bot=object(), message=SimpleNamespace(chat=SimpleNamespace(id=42)))
|
||||
asyncio.run(_exec("cb_rank_stats", ns)(callback))
|
||||
text = "\n".join(pages[0])
|
||||
assert "ранг N открывает модели рангов 1…N" in text
|
||||
assert "не гарантирует работоспособность" in text
|
||||
assert "а не доступ к семействам" not in text
|
||||
|
||||
|
||||
def test_generation_error_text_sanitised():
|
||||
ns = {"GenerationError": type("GenerationError", (RuntimeError,), {})}
|
||||
fn = _exec("_gen_err_user_text", ns)
|
||||
GE = ns["GenerationError"]
|
||||
msg = "Выбранная модель сейчас занята. Повтори немного позже."
|
||||
assert fn(GE(msg)) == msg
|
||||
assert fn(RuntimeError(msg)) == ""
|
||||
assert fn(GE("https://gw.local/v1?key=secret")) == ""
|
||||
assert fn(GE("<b>boom</b>")) == ""
|
||||
assert fn(GE("x" * 500)) == ""
|
||||
@@ -0,0 +1,350 @@
|
||||
"""Casino removal & settlement-only jackpot: behaviour tests over the live bot source.
|
||||
|
||||
Source-only (AST) tests: no bot DB, no network, no aiogram runtime.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import asyncio
|
||||
import copy
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BOT = ROOT / "bot" / "grok_bot.py"
|
||||
PANELS_SRC = (ROOT / "bot" / "forum_panels.py").read_text(encoding="utf-8")
|
||||
SRC = BOT.read_text(encoding="utf-8")
|
||||
TREE = ast.parse(SRC)
|
||||
|
||||
|
||||
def _fn(name):
|
||||
for node in TREE.body:
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:
|
||||
return node
|
||||
raise AssertionError(f"{name} not found in bot/grok_bot.py")
|
||||
|
||||
|
||||
def _exec(names, ns):
|
||||
# aiogram-декораторы исполнялись бы против несуществующего `router`:
|
||||
# копируем узлы и снимаем decorator_list (источник не меняем).
|
||||
body = []
|
||||
for name in names:
|
||||
node = copy.deepcopy(_fn(name))
|
||||
node.decorator_list = []
|
||||
body.append(node)
|
||||
mod = ast.Module(body=body, type_ignores=[])
|
||||
exec(compile(ast.fix_missing_locations(mod), "<bot>", "exec"), ns)
|
||||
return ns
|
||||
|
||||
|
||||
class FakeMessage:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
self.chat = type("C", (), {"id": 1})()
|
||||
self.from_user = type("U", (), {"id": 1})()
|
||||
|
||||
async def answer(self, text, **kw):
|
||||
self.sent.append((text, kw))
|
||||
return self
|
||||
|
||||
|
||||
class FakeQuery:
|
||||
def __init__(self):
|
||||
self.answers = []
|
||||
self.message = FakeMessage()
|
||||
self.from_user = type("U", (), {"id": 1})()
|
||||
|
||||
async def answer(self, text=None, **kw):
|
||||
self.answers.append((text, kw))
|
||||
|
||||
|
||||
def _trap(*_a, **_k):
|
||||
raise AssertionError("finance/DB helper must not be called by a removed feature")
|
||||
|
||||
|
||||
def _ns():
|
||||
return {
|
||||
"Message": FakeMessage,
|
||||
"CallbackQuery": FakeQuery,
|
||||
"log": type("L", (), {"debug": staticmethod(lambda *a, **k: None),
|
||||
"info": staticmethod(lambda *a, **k: None),
|
||||
"warning": staticmethod(lambda *a, **k: None),
|
||||
"exception": staticmethod(lambda *a, **k: None)})(),
|
||||
"_cas_wallet": _trap,
|
||||
"_cas_sub_cents": _trap,
|
||||
"_cas_add_cents": _trap,
|
||||
"_jpot_db": _trap,
|
||||
"_jpot_start_round": _trap,
|
||||
"_jpot_announce_result": _trap,
|
||||
}
|
||||
|
||||
|
||||
def _call_names(node):
|
||||
out = set()
|
||||
for sub in ast.walk(node):
|
||||
if isinstance(sub, ast.Call):
|
||||
f = sub.func
|
||||
if isinstance(f, ast.Name):
|
||||
out.add(f.id)
|
||||
elif isinstance(f, ast.Attribute):
|
||||
out.add(f.attr)
|
||||
return out
|
||||
|
||||
|
||||
def test_casino_block_removed():
|
||||
for name in ("_CAS_BETS", "_CAS_CD", "_cas_get_cents", "_cas_menu_kb", "_cas_bet_kb",
|
||||
"_cb_casino_inner", "_cas_play_slot", "_cas_play_dice", "_cas_play_roul"):
|
||||
assert name not in SRC, name
|
||||
assert "/casino — слоты" not in SRC
|
||||
assert "🎰 /casino" not in SRC
|
||||
|
||||
|
||||
def test_casino_stub_answers_without_finance():
|
||||
ns = _exec(["cmd_casino", "cb_casino"], _ns())
|
||||
msg = FakeMessage()
|
||||
asyncio.run(ns["cmd_casino"](msg))
|
||||
assert msg.sent and msg.sent[0][0]
|
||||
|
||||
q = FakeQuery()
|
||||
asyncio.run(ns["cb_casino"](q))
|
||||
assert q.answers and q.answers[0][0]
|
||||
|
||||
|
||||
def test_jackpot_creates_nothing():
|
||||
for node in TREE.body:
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in (
|
||||
"cmd_jpot", "cmd_jpot_now", "_jpot_cb_inner", "cmd_jpot_settle"):
|
||||
calls = _call_names(node)
|
||||
assert "_jpot_start_round" not in calls, node.name
|
||||
assert "_jpot_announce_result" not in calls, node.name
|
||||
|
||||
|
||||
def test_cas_fmt_still_shared():
|
||||
ns = _exec(["_cas_fmt"], _ns())
|
||||
assert ns["_cas_fmt"](150) == "$1.50"
|
||||
|
||||
|
||||
def test_panels_and_topics_in_sync():
|
||||
econ = None
|
||||
for node in TREE.body:
|
||||
if isinstance(node, ast.Assign) and any(
|
||||
isinstance(t, ast.Name) and t.id == "ECON_PANELS" for t in node.targets):
|
||||
econ = ast.literal_eval(node.value)
|
||||
assert econ is not None, "ECON_PANELS not found"
|
||||
assert "casino" not in econ
|
||||
topics = None
|
||||
for node in ast.parse(PANELS_SRC).body:
|
||||
if isinstance(node, ast.Assign) and any(
|
||||
isinstance(t, ast.Name) and t.id == "TOPICS" for t in node.targets):
|
||||
topics = ast.literal_eval(node.value)
|
||||
assert topics is not None
|
||||
assert "casino" not in {k for k, _ in topics}
|
||||
assert {k for k, _ in topics} == set(econ)
|
||||
|
||||
|
||||
class FakeBot:
|
||||
"""Записывает вызовы Telegram; падение задаётся через `fail`."""
|
||||
|
||||
def __init__(self, fail=None):
|
||||
self.calls = []
|
||||
self.fail = fail or {}
|
||||
|
||||
async def edit_message_reply_markup(self, **kw):
|
||||
self.calls.append(("markup", kw))
|
||||
if "markup" in self.fail:
|
||||
raise self.fail["markup"]
|
||||
|
||||
async def send_message(self, chat_id, text=None, **kw):
|
||||
self.calls.append(("send", {"chat_id": chat_id, "text": text, **kw}))
|
||||
if "send" in self.fail:
|
||||
raise self.fail["send"]
|
||||
return type("M", (), {"message_id": 99})()
|
||||
|
||||
async def edit_message_text(self, **kw):
|
||||
self.calls.append(("text", kw))
|
||||
if "text" in self.fail:
|
||||
raise self.fail["text"]
|
||||
|
||||
def sent(self):
|
||||
return [c[1]["text"] for c in self.calls if c[0] == "send"]
|
||||
|
||||
|
||||
def _closure_env(settle_row=(7,), bot=None):
|
||||
ns = _ns()
|
||||
ns["_cas_fmt"] = _exec(["_cas_fmt"], _ns())["_cas_fmt"]
|
||||
ns["_jpot_db"] = lambda: con
|
||||
return ns
|
||||
|
||||
|
||||
def test_jpot_closure_notifier_paid_reports_once():
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)")
|
||||
con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 4242)")
|
||||
ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"],
|
||||
"_jpot_db": lambda: con,
|
||||
"log": _ns()["log"]}
|
||||
_exec(["_jpot_closure_notify"], ns)
|
||||
fn = ns["_jpot_closure_notify"]
|
||||
bot = FakeBot()
|
||||
asyncio.run(fn(bot, 7, {"chat_id": 10, "pot": 5100, "paid": True, "outcome": "win"}))
|
||||
kinds = [c[0] for c in bot.calls]
|
||||
assert kinds == ["markup", "send"], kinds
|
||||
assert bot.calls[0][1]["message_id"] == 4242
|
||||
assert bot.calls[0][1]["reply_markup"] is None
|
||||
text = bot.sent()[0]
|
||||
assert "#7" in text and "$51.00" in text
|
||||
assert "_jpot_announce_result" not in text
|
||||
con.close()
|
||||
|
||||
|
||||
def test_jpot_closure_notifier_unpaid_only_strips_keyboard():
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)")
|
||||
con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 5)")
|
||||
ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"],
|
||||
"_jpot_db": lambda: con,
|
||||
"log": _ns()["log"]}
|
||||
_exec(["_jpot_closure_notify"], ns)
|
||||
fn = ns["_jpot_closure_notify"]
|
||||
bot = FakeBot()
|
||||
asyncio.run(fn(bot, 7, {"chat_id": 10, "pot": 0, "outcome": "empty"}))
|
||||
assert [c[0] for c in bot.calls] == ["markup"]
|
||||
asyncio.run(fn(bot, 7, None))
|
||||
assert [c[0] for c in bot.calls] == ["markup"]
|
||||
con.close()
|
||||
|
||||
|
||||
def test_jpot_closure_notifier_survives_telegram_errors():
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, msg_id INTEGER)")
|
||||
con.execute("INSERT INTO jpot_rounds(id, msg_id) VALUES(7, 5)")
|
||||
ns = {"_cas_fmt": _exec(["_cas_fmt"], _ns())["_cas_fmt"],
|
||||
"_jpot_db": lambda: con,
|
||||
"log": _ns()["log"]}
|
||||
_exec(["_jpot_closure_notify"], ns)
|
||||
bot = FakeBot(fail={"markup": RuntimeError("message to edit not found"),
|
||||
"send": RuntimeError("chat not found")})
|
||||
asyncio.run(ns["_jpot_closure_notify"](bot, 7, {"chat_id": 10, "pot": 100, "paid": True}))
|
||||
assert [c[0] for c in bot.calls] == ["markup", "send"]
|
||||
con.close()
|
||||
|
||||
|
||||
def test_worker_and_admin_settle_notify_closure():
|
||||
worker = _fn("_jpot_worker")
|
||||
calls = _call_names(worker)
|
||||
assert "_jpot_settle" in calls and "_jpot_closure_notify" in calls
|
||||
assert "_jpot_announce_result" not in calls and "_jpot_start_round" not in calls
|
||||
assert "_jpot_closure_notify" in _call_names(_fn("cmd_jpot_settle"))
|
||||
|
||||
|
||||
def test_jpot_settle_command_reports_already_closed_without_outcome():
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("CREATE TABLE jpot_rounds(id INTEGER PRIMARY KEY, status INTEGER, chat_id INTEGER)")
|
||||
con.execute("INSERT INTO jpot_rounds(id, status, chat_id) VALUES(3, 0, 1)")
|
||||
ns = _ns()
|
||||
ns["_jpot_db"] = lambda: con
|
||||
ns["_jpot_is_admin"] = lambda uid: True
|
||||
ns["_jpot_settle"] = lambda rid: None
|
||||
ns["_jpot_closure_notify"] = _trap
|
||||
_exec(["cmd_jpot_settle"], ns)
|
||||
msg = FakeMessage()
|
||||
asyncio.run(ns["cmd_jpot_settle"](msg))
|
||||
text = msg.sent[-1][0]
|
||||
assert "уже закрыт" in text
|
||||
assert "None" not in text and "outcome" not in text
|
||||
con.close()
|
||||
|
||||
|
||||
def test_jpot_stub_strips_stale_keyboard_and_survives_expired_callback():
|
||||
ns = _ns()
|
||||
_exec(["_jpot_cb_inner"], ns)
|
||||
q = FakeQuery()
|
||||
stripped = []
|
||||
|
||||
async def edit_reply_markup(**kw):
|
||||
stripped.append(kw)
|
||||
|
||||
q.message.edit_reply_markup = edit_reply_markup
|
||||
asyncio.run(ns["_jpot_cb_inner"](q))
|
||||
assert stripped and stripped[0]["reply_markup"] is None
|
||||
assert q.answers and "отключён" in q.answers[0][0]
|
||||
|
||||
class Expired(FakeQuery):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.message = None
|
||||
|
||||
async def answer(self, text=None, **kw):
|
||||
raise RuntimeError("query is too old and response timeout expired")
|
||||
|
||||
asyncio.run(ns["_jpot_cb_inner"](Expired()))
|
||||
|
||||
|
||||
def _panels_ns():
|
||||
ns = {"__name__": "forum_panels_under_test"}
|
||||
exec(compile(PANELS_SRC, "forum_panels.py", "exec"), ns)
|
||||
return ns
|
||||
|
||||
|
||||
def _forum_db(directory):
|
||||
path = Path(directory) / "bot.db"
|
||||
con = sqlite3.connect(path)
|
||||
con.execute("""CREATE TABLE forum_topics(chat_id INTEGER NOT NULL, kind TEXT NOT NULL,
|
||||
thread_id INTEGER NOT NULL, title TEXT NOT NULL, panel_message_id INTEGER,
|
||||
created INTEGER NOT NULL, PRIMARY KEY(chat_id,kind), UNIQUE(chat_id,thread_id))""")
|
||||
con.commit()
|
||||
con.close()
|
||||
return path
|
||||
|
||||
|
||||
def test_retire_casino_panels_idempotent_and_metadata_only(tmp_path):
|
||||
ns = _panels_ns()
|
||||
db = _forum_db(tmp_path)
|
||||
con = sqlite3.connect(db)
|
||||
con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)"
|
||||
" VALUES(10,'casino',77,'🎰 Казино',555,1)")
|
||||
con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)"
|
||||
" VALUES(10,'econ',78,'💰 Экономика',556,1)")
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
bot = FakeBot()
|
||||
res = asyncio.run(ns["retire_casino_panels"](db, bot))
|
||||
assert res == {"found": 1, "retired": 1, "failed": 0}, res
|
||||
assert [c[0] for c in bot.calls] == ["text"]
|
||||
kw = bot.calls[0][1]
|
||||
assert kw["message_id"] == 555 and kw["reply_markup"] is None and kw["chat_id"] == 10
|
||||
con = sqlite3.connect(db)
|
||||
kinds = {r[0] for r in con.execute("SELECT kind FROM forum_topics")}
|
||||
con.close()
|
||||
assert kinds == {"econ"}
|
||||
|
||||
bot2 = FakeBot()
|
||||
assert asyncio.run(ns["retire_casino_panels"](db, bot2)) == {"found": 0, "retired": 0, "failed": 0}
|
||||
assert bot2.calls == []
|
||||
|
||||
|
||||
def test_retire_casino_panels_keeps_row_when_edit_fails_hard(tmp_path):
|
||||
ns = _panels_ns()
|
||||
db = _forum_db(tmp_path)
|
||||
con = sqlite3.connect(db)
|
||||
con.execute("INSERT INTO forum_topics(chat_id,kind,thread_id,title,panel_message_id,created)"
|
||||
" VALUES(10,'casino',77,'🎰 Казино',555,1)")
|
||||
con.commit()
|
||||
con.close()
|
||||
res = asyncio.run(ns["retire_casino_panels"](db, FakeBot(fail={"text": RuntimeError("chat not found")})))
|
||||
assert res["found"] == 1 and res["retired"] == 0 and res["failed"] == 1, res
|
||||
con = sqlite3.connect(db)
|
||||
assert con.execute("SELECT COUNT(*) FROM forum_topics WHERE kind='casino'").fetchone()[0] == 1
|
||||
con.close()
|
||||
|
||||
gone = asyncio.run(ns["retire_casino_panels"](
|
||||
db, FakeBot(fail={"text": RuntimeError("message to edit not found")})))
|
||||
assert gone["retired"] == 1 and gone["failed"] == 0, gone
|
||||
|
||||
|
||||
def test_setup_retires_stale_casino_rows():
|
||||
src = ast.parse(PANELS_SRC)
|
||||
setup = next(n for n in src.body if getattr(n, "name", "") == "_setup")
|
||||
assert "retire_casino_panels" in _call_names(setup)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""No bot imports: trusted rank catalogue and expired-pass permission contracts."""
|
||||
from contextlib import closing
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'bot'))
|
||||
import commerce_access
|
||||
import gateway_commerce
|
||||
|
||||
|
||||
class CommerceAccessTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.db = str(self.root / 'bot.db')
|
||||
source = self.root / 'trusted_bot.py'
|
||||
source.write_text("raise RuntimeError('must never import bot')\n"
|
||||
"TIER_MODELS={1:['base'],2:['active'],3:['pro'],4:['premium']}\n"
|
||||
"BADGES={1:('', '',0,0),2:('', '',5,7),3:('', '',15,21),4:('', '',40,48)}\n"
|
||||
"RANK_REFS={2:2,3:5,4:10}\nADMIN_IDS={999}\n"
|
||||
"MODEL_DESCS={'premium':'Premium'}\n", encoding='utf-8')
|
||||
env = patch.dict(os.environ, {'IISHKO_BOT_SOURCE': str(source), 'IISHKO_ADMIN_IDS': '999'})
|
||||
env.start()
|
||||
self.addCleanup(env.stop)
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.executescript('CREATE TABLE users(tg_id INTEGER PRIMARY KEY,banned INTEGER DEFAULT 0,'
|
||||
'api_blocked INTEGER DEFAULT 0,admin INTEGER DEFAULT 0,created INTEGER DEFAULT 0,'
|
||||
'rep INTEGER DEFAULT 0,referred_by INTEGER,ref_awarded INTEGER DEFAULT 0,'
|
||||
'badge_lock INTEGER DEFAULT 0,badge_until INTEGER DEFAULT 0);'
|
||||
'INSERT INTO users(tg_id) VALUES(123),(999);')
|
||||
gateway_commerce.init_db(self.db)
|
||||
|
||||
def sql(self, query, params=()):
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
result = con.execute(query, params).fetchall()
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
def grant(self, expires):
|
||||
self.sql("INSERT INTO commerce_grants(uid,kind,model,expires_at,request_id,created) "
|
||||
"VALUES(123,'model_pass','premium',?,'offline-pass-id',0)", (expires,))
|
||||
|
||||
def test_base_access_is_from_rank_not_stale_rank_cache_or_token_list(self):
|
||||
self.assertEqual(commerce_access.base_models(self.db, 123), ['base'])
|
||||
self.assertEqual(commerce_access.base_models(self.db, 999), ['base', 'active', 'pro', 'premium'])
|
||||
self.sql('UPDATE users SET created=?,rep=5 WHERE tg_id=123', (int(time.time())-8*86400,))
|
||||
self.assertEqual(commerce_access.base_models(self.db, 123), ['base', 'active'])
|
||||
|
||||
def test_expired_paid_model_cannot_use_stale_upstream_model_limits(self):
|
||||
self.grant(int(time.time())-1)
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'premium', ['base','premium'], True))
|
||||
self.assertTrue(commerce_access.allowed(self.db, 123, 'base', ['base','premium'], True))
|
||||
self.sql('UPDATE users SET badge_lock=4 WHERE tg_id=123')
|
||||
self.assertTrue(commerce_access.allowed(self.db, 123, 'premium', ['base','premium'], True))
|
||||
self.sql('UPDATE users SET badge_until=? WHERE tg_id=123', (int(time.time())-1,))
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'premium', ['base','premium'], True))
|
||||
|
||||
def test_active_pass_is_additive_but_never_a_ban_or_subscription_override(self):
|
||||
self.grant(int(time.time())+86400)
|
||||
self.assertTrue(commerce_access.allowed(self.db, 123, 'premium', ['base'], False))
|
||||
for flag in ('banned', 'api_blocked'):
|
||||
self.sql('UPDATE users SET '+flag+'=1 WHERE tg_id=123')
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'premium', ['base'], False))
|
||||
self.sql('UPDATE users SET '+flag+'=0 WHERE tg_id=123')
|
||||
|
||||
def test_unmanaged_manual_token_limits_remain_unchanged_and_errors_fail_closed(self):
|
||||
# A model OUTSIDE the operator catalogue is a genuine provider passthrough; the
|
||||
# token's own model_limits gate is honoured unchanged.
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'passthrough-x', ['base'], False))
|
||||
self.assertTrue(commerce_access.allowed(self.db, 123, 'passthrough-x', ['base', 'passthrough-x'], True))
|
||||
# limit: rank-1 uid 123 has no 'pro' by live rank or active pass, so it fails
|
||||
# closed even when the token cache still lists it (stale secondary-token leak).
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'pro', ['base'], False))
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'pro', ['base', 'pro'], True))
|
||||
self.grant(int(time.time()) + 86400)
|
||||
with patch.dict(os.environ, {'IISHKO_BOT_SOURCE': str(self.root / 'missing.py')}):
|
||||
self.assertFalse(commerce_access.allowed(self.db, 123, 'premium', ['premium'], True))
|
||||
|
||||
def test_default_source_is_implementation_not_compatibility_launcher(self):
|
||||
(self.root / 'grok_bot.py').write_text((self.root / 'trusted_bot.py').read_text(encoding='utf-8'), encoding='utf-8')
|
||||
(self.root / 'iishko_bot.py').write_text('from grok_bot import *', encoding='utf-8')
|
||||
with patch.dict(os.environ, {'IISHKO_BOT_SOURCE': '', 'IISHKO_APP_ROOT': str(self.root)}):
|
||||
self.assertEqual(commerce_access._source(), self.root / 'grok_bot.py')
|
||||
self.assertIn('premium', commerce_access.public_models())
|
||||
|
||||
def test_env_admin_expression_and_literal_image_concatenation_are_safe(self):
|
||||
source = self.root / 'trusted_bot.py'
|
||||
source.write_text(source.read_text(encoding='utf-8') +
|
||||
"ADMIN_IDS={int(v) for v in ['ignored']}\n"
|
||||
"BG_IMG_MODELS=['image-b']\nIMG_MODELS=['image-a']+BG_IMG_MODELS\n",
|
||||
encoding='utf-8')
|
||||
self.assertTrue({'image-a', 'image-b'} <= commerce_access.public_models())
|
||||
self.assertEqual(commerce_access.base_models(self.db, 999)[:4], ['base','active','pro','premium'])
|
||||
|
||||
def test_actual_packaged_catalogue_is_read_without_importing_bot(self):
|
||||
with patch.dict(os.environ, {'IISHKO_BOT_SOURCE': str(ROOT / 'bot/grok_bot.py')}):
|
||||
models = commerce_access.public_models()
|
||||
self.assertGreater(len(models), 20)
|
||||
self.assertTrue(all(isinstance(model, str) and model for model in models))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Actual scoped HTTP handlers with signed initData, isolated DBs and no bot import."""
|
||||
import ast
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock
|
||||
from urllib.parse import parse_qsl, urlencode
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'bot'))
|
||||
import account_balances
|
||||
import gateway_commerce
|
||||
|
||||
TOKEN = '123456:offline-http-token'
|
||||
|
||||
|
||||
def signed(uid=123):
|
||||
data = {'auth_date':str(int(time.time())), 'user':json.dumps({'id':uid})}
|
||||
secret = hmac.new(b'WebAppData', TOKEN.encode(), hashlib.sha256).digest()
|
||||
data['hash'] = hmac.new(secret, '\n'.join(key+'='+data[key] for key in sorted(data)).encode(), hashlib.sha256).hexdigest()
|
||||
return urlencode(data)
|
||||
|
||||
|
||||
class CommerceHTTPTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.db = str(Path(temp.name)/'bot.db')
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.executescript('CREATE TABLE users(tg_id INTEGER PRIMARY KEY,banned INTEGER DEFAULT 0,api_blocked INTEGER DEFAULT 0);'
|
||||
'INSERT INTO users(tg_id) VALUES(123),(456);')
|
||||
gateway_commerce.init_db(self.db)
|
||||
functions = {'verify_init','_con','_keys_body','_keys_error','_keys_response','_feature_error',
|
||||
'api_commerce','api_commerce_action','api_keys_return_all'}
|
||||
tree = ast.parse((ROOT/'bot/webapp/server.py').read_text(encoding='utf-8'))
|
||||
nodes = [node for node in tree.body if isinstance(node,(ast.FunctionDef,ast.AsyncFunctionDef)) and node.name in functions]
|
||||
self.mk = SimpleNamespace(call=AsyncMock(return_value={'ok':True,'moved_usd':5,'total_balance_usd':10}))
|
||||
self.ns = dict(globals(), BOT_DB=self.db, BOT_TOKEN=TOKEN, CFG={}, MK=self.mk,
|
||||
commerce_access=SimpleNamespace(base_models=lambda db,uid:[], public_models=lambda: frozenset({'known-model'})),
|
||||
_sync_commerce_models=lambda uid:None, _econ_invalidate=lambda uid:None)
|
||||
exec(compile(ast.Module(body=nodes,type_ignores=[]), 'scoped-http-handlers', 'exec'), self.ns)
|
||||
@web.middleware
|
||||
async def auth(request, handler):
|
||||
uid = self.ns['verify_init'](request.headers.get('X-Init-Data',''))
|
||||
if uid is None:
|
||||
return web.json_response({'error':'unauthorized'},status=401)
|
||||
request['uid'] = uid
|
||||
return await handler(request)
|
||||
app = web.Application(middlewares=[auth])
|
||||
app.router.add_get('/api/commerce', self.ns['api_commerce'])
|
||||
app.router.add_post('/api/commerce/action', self.ns['api_commerce_action'])
|
||||
app.router.add_post('/api/keys/return_all', self.ns['api_keys_return_all'])
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
self.addAsyncCleanup(self.client.close)
|
||||
|
||||
async def post(self,path,body,uid=123):
|
||||
response = await self.client.post(path,json=body,headers={'X-Init-Data':signed(uid)})
|
||||
return response, await response.json()
|
||||
|
||||
async def test_auth_and_unavailable_snapshot_are_explicit(self):
|
||||
response = await self.client.get('/api/commerce')
|
||||
self.assertEqual(response.status,401)
|
||||
response = await self.client.get('/api/commerce',headers={'X-Init-Data':signed()})
|
||||
self.assertEqual(response.status,200)
|
||||
state = await response.json()
|
||||
self.assertEqual(state['uid'],123)
|
||||
self.assertEqual(state['currency'],'USD')
|
||||
self.assertEqual(state['wallet_cents'],0)
|
||||
self.assertFalse(state['payment_enabled'])
|
||||
response, body = await self.post('/api/commerce/action',{
|
||||
'action':'purchase','offer_id':'offline-offer','request_id':'unavailable-http-id'})
|
||||
self.assertEqual(response.status,503)
|
||||
self.assertEqual(body['error'],'commerce_unavailable')
|
||||
self.assertIn('msg',body)
|
||||
self.assertFalse(body['operation_rejected'])
|
||||
|
||||
async def test_purchase_receipts_and_ban_gate_use_signed_user_not_body_identity(self):
|
||||
self.ns['CFG']['commerce_offers']=[{'id':'offline-offer','kind':'extra_requests','price_cents':100,'requests':20}]
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.execute('INSERT INTO commerce_wallets VALUES(123,200)')
|
||||
con.commit()
|
||||
request={'action':'purchase','offer_id':'offline-offer','request_id':'http-purchase-replay'}
|
||||
response, body=await self.post('/api/commerce/action',dict(request,uid=456))
|
||||
self.assertEqual(response.status,400)
|
||||
self.assertTrue(body['operation_rejected'])
|
||||
response, body=await self.post('/api/commerce/action',request)
|
||||
self.assertEqual(response.status,200)
|
||||
self.assertEqual(body['state']['uid'],123)
|
||||
self.assertEqual(body['state']['wallet_cents'],100)
|
||||
response, body=await self.post('/api/commerce/action',request)
|
||||
self.assertEqual(response.status,200)
|
||||
self.assertTrue(body['replayed'])
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.execute('UPDATE users SET banned=1 WHERE tg_id=123')
|
||||
con.commit()
|
||||
response, body=await self.post('/api/commerce/action',request)
|
||||
self.assertEqual(response.status,403)
|
||||
self.assertEqual(body['error'],'blocked')
|
||||
self.assertFalse(body['operation_rejected'])
|
||||
|
||||
async def test_aggregate_return_uses_request_id_only_and_never_dispatches_delete(self):
|
||||
request={'request_id':'http-return-all-id'}
|
||||
response,body=await self.post('/api/keys/return_all',request)
|
||||
self.assertEqual(response.status,200)
|
||||
self.assertEqual(body['total_balance_usd'],10)
|
||||
self.mk.call.assert_awaited_once_with('return_all',uid=123,request_id=request['request_id'])
|
||||
response,body=await self.post('/api/keys/return_all',dict(request,uid=456,n=2))
|
||||
self.assertEqual(response.status,400)
|
||||
self.assertTrue(body['operation_rejected'])
|
||||
self.assertEqual(self.mk.call.await_count,1)
|
||||
|
||||
async def test_unknown_configured_model_offer_never_debits_wallet(self):
|
||||
self.ns['CFG']['commerce_offers'] = [
|
||||
{'id':'unknown-pass','kind':'model_pass','price_cents':100,'model':'unknown-model'}]
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute('INSERT INTO commerce_wallets VALUES(123,200)')
|
||||
response, body = await self.post('/api/commerce/action',
|
||||
{'action':'purchase','offer_id':'unknown-pass','request_id':'unknown-model-http-id'})
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertEqual(body['error'], 'model_offer_unavailable')
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
self.assertEqual(con.execute('SELECT balance_cents FROM commerce_wallets WHERE uid=123').fetchone()[0],200)
|
||||
self.assertEqual(con.execute('SELECT count(*) FROM commerce_grants').fetchone()[0],0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,686 @@
|
||||
"""SQLite contracts for private intake, independent review and one-time reputation."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import itertools
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'bot'))
|
||||
import community_board as board
|
||||
|
||||
|
||||
class CommunityBoardTests(unittest.TestCase):
|
||||
BASE_REP = 7
|
||||
NOW = 1_800_000_000
|
||||
ITEM_FIELDS = {'id', 'kind', 'category', 'title', 'description', 'proof', 'status',
|
||||
'author_uid', 'reward_rep', 'created_at', 'review_reason'}
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.db = Path(self.tmp.name) / 'bot.db'
|
||||
self.ids = itertools.count()
|
||||
self.admins = (1, 4)
|
||||
self.time_patch = patch.object(board.time, 'time', return_value=self.NOW)
|
||||
self.clock = self.time_patch.start()
|
||||
self.addCleanup(self.time_patch.stop)
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.execute('CREATE TABLE users(tg_id INTEGER PRIMARY KEY,banned INTEGER DEFAULT 0,'
|
||||
'api_blocked INTEGER DEFAULT 0,rep INTEGER DEFAULT 7,'
|
||||
'legacy_balance INTEGER DEFAULT 777,points INTEGER DEFAULT 23)')
|
||||
con.executemany('INSERT INTO users(tg_id) VALUES(?)', [(uid,) for uid in range(1, 9)])
|
||||
con.execute('CREATE TABLE community_wallets(uid INTEGER PRIMARY KEY,balance INTEGER NOT NULL)')
|
||||
con.executemany('INSERT INTO community_wallets(uid,balance) VALUES(?,?)',
|
||||
[(uid, 100 + uid) for uid in range(1, 9)])
|
||||
con.commit()
|
||||
board.init_db(self.db)
|
||||
|
||||
def submission_body(self, **changes):
|
||||
body = {'action': 'submit', 'kind': 'activity', 'category': 'docs',
|
||||
'title': 'Reproducible integration instructions',
|
||||
'description': 'A verified guide with reproducible steps, expected results and working examples.',
|
||||
'proof': 'docs.example.test/guide and API request_id safe-example-123',
|
||||
'request_id': f'board-test-{next(self.ids):08d}'}
|
||||
body.update(changes)
|
||||
return body
|
||||
|
||||
def review_body(self, submission_id, **changes):
|
||||
body = {'action': 'review', 'id': submission_id, 'decision': 'accepted',
|
||||
'reward_rep': 10, 'reason': 'Independently verified useful contribution and reproducible evidence.',
|
||||
'request_id': f'board-review-{next(self.ids):08d}'}
|
||||
body.update(changes)
|
||||
return body
|
||||
|
||||
def submit(self, uid=2, **changes):
|
||||
return board.act(self.db, uid, self.submission_body(**changes), self.admins)
|
||||
|
||||
def review(self, submission_id, uid=1, **changes):
|
||||
return board.act(self.db, uid, self.review_body(submission_id, **changes), self.admins)
|
||||
|
||||
def state(self, uid=2, admins=None):
|
||||
return board.snapshot(self.db, uid, self.admins if admins is None else admins)
|
||||
|
||||
def rows(self, sql, parameters=()):
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
return con.execute(sql, parameters).fetchall()
|
||||
|
||||
def execute(self, sql, parameters=()):
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.execute(sql, parameters)
|
||||
con.commit()
|
||||
|
||||
def count(self, table):
|
||||
return self.rows('SELECT COUNT(*) FROM ' + table)[0][0]
|
||||
|
||||
def rep(self, uid=2):
|
||||
return self.rows('SELECT rep FROM users WHERE tg_id=?', (uid,))[0][0]
|
||||
|
||||
def assert_error(self, status, code, call, operation_rejected=None):
|
||||
with self.assertRaises(board.BoardError) as ctx:
|
||||
call()
|
||||
error = ctx.exception
|
||||
self.assertEqual((error.status, error.code), (status, code))
|
||||
self.assertEqual(str(error), error.message)
|
||||
self.assertTrue(error.message)
|
||||
if operation_rejected is not None:
|
||||
self.assertIs(error.operation_rejected, operation_rejected)
|
||||
return error
|
||||
|
||||
def test_snapshot_shape_rules_and_submission_do_not_automatically_award_rep(self):
|
||||
initial = self.state()
|
||||
self.assertEqual(set(initial), {'uid', 'is_admin', 'activities', 'own_submissions',
|
||||
'review_queue', 'rules', 'reputation'})
|
||||
self.assertEqual((initial['uid'], initial['is_admin'], initial['reputation']), (2, False, self.BASE_REP))
|
||||
result = self.submit()
|
||||
self.assertEqual(result, {'ok': True, 'action': 'submit', 'id': result['id'],
|
||||
'status': 'pending', 'reward_rep': 0})
|
||||
own = self.state()['own_submissions']
|
||||
self.assertEqual(set(own[0]), self.ITEM_FIELDS)
|
||||
self.assertEqual((own[0]['author_uid'], own[0]['created_at'], own[0]['review_reason']),
|
||||
(2, self.NOW, ''))
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
self.assertEqual(self.state()['activities'], [])
|
||||
rules = initial['rules']
|
||||
self.assertEqual(rules['activity_categories'], list(board.ACTIVITY_CATEGORIES))
|
||||
self.assertEqual(rules['bug_severities'], list(board.BUG_SEVERITIES))
|
||||
self.assertFalse(rules['cash_bounty'])
|
||||
self.assertFalse(rules['reward_rep']['automatic_for_messages'])
|
||||
self.assertTrue(rules['reward_rep']['after_review_only'])
|
||||
self.assertEqual(rules['reward_rep']['max'], 40)
|
||||
self.assertIn('воспроизводимые шаги', rules['submission_guide']['bug'])
|
||||
self.assertIn('ожидаемый и фактический', rules['submission_guide']['bug'])
|
||||
self.assertEqual(len(rules['rubric']), 8)
|
||||
self.assertTrue(all(row['example'] for row in rules['rubric']))
|
||||
rules['activity_categories'].clear()
|
||||
rules['rubric'][0]['suggested_rep'][1] = 999
|
||||
self.assertEqual(len(self.state()['rules']['activity_categories']), 4)
|
||||
self.assertLessEqual(self.state()['rules']['rubric'][0]['suggested_rep'][1], 40)
|
||||
|
||||
def test_pending_and_rejected_activity_are_author_only_except_admin_queue(self):
|
||||
first = self.submit(title='PRIVATE_PENDING_ACTIVITY')
|
||||
second = self.submit(uid=3, title='OTHER_PENDING_ACTIVITY')
|
||||
self.assertEqual([item['id'] for item in self.state(2)['own_submissions']], [first['id']])
|
||||
self.assertEqual([item['id'] for item in self.state(3)['own_submissions']], [second['id']])
|
||||
outsider = self.state(5)
|
||||
self.assertEqual(outsider['activities'], [])
|
||||
self.assertEqual(outsider['own_submissions'], [])
|
||||
self.assertEqual(outsider['review_queue'], [])
|
||||
self.assertNotIn('PRIVATE_PENDING_ACTIVITY', json.dumps(outsider))
|
||||
queue = self.state(1)['review_queue']
|
||||
self.assertEqual([item['id'] for item in queue], [first['id'], second['id']])
|
||||
self.review(first['id'], decision='rejected', reward_rep=0, reason='Not reproducible on the stated version.')
|
||||
own = self.state(2)['own_submissions'][0]
|
||||
self.assertEqual(own['status'], 'rejected')
|
||||
self.assertTrue(own['review_reason'])
|
||||
self.assertEqual(self.state(5)['activities'], [])
|
||||
self.assertEqual([item['id'] for item in self.state(1)['review_queue']], [second['id']])
|
||||
|
||||
def test_accepted_activity_feed_contains_only_accepted_public_items(self):
|
||||
public = self.submit(title='Public accepted documentation')
|
||||
self.submit(uid=3, title='Not accepted documentation')
|
||||
self.review(public['id'], reward_rep=9, reason='Instructions verified independently on a clean environment.')
|
||||
for uid in (1, 2, 3, 5):
|
||||
feed = self.state(uid)['activities']
|
||||
self.assertEqual([item['id'] for item in feed], [public['id']])
|
||||
self.assertEqual((feed[0]['kind'], feed[0]['status'], feed[0]['reward_rep']),
|
||||
('activity', 'accepted', 9))
|
||||
self.assertEqual(set(feed[0]), self.ITEM_FIELDS)
|
||||
self.assertEqual(self.state(2)['reputation'], self.BASE_REP + 9)
|
||||
|
||||
def test_bug_body_title_proof_and_review_reason_never_leak_to_other_users_or_feed(self):
|
||||
private = {
|
||||
'kind': 'bug', 'category': 'high', 'title': 'BUG_PRIVATE_TITLE_MARKER',
|
||||
'description': 'BUG_PRIVATE_BODY_MARKER: steps 1, 2. Expected denial; actual permission accepted.',
|
||||
'proof': 'BUG_PRIVATE_PROOF_MARKER / request_id private-proof-example',
|
||||
}
|
||||
report = self.submit(**private)
|
||||
author = self.state(2)
|
||||
admin = self.state(1)
|
||||
self.assertEqual(author['own_submissions'][0]['description'], private['description'])
|
||||
self.assertEqual(admin['review_queue'][0]['proof'], private['proof'])
|
||||
for uid in (3, 5, 8):
|
||||
serialized = json.dumps(self.state(uid), ensure_ascii=False)
|
||||
for value in private.values():
|
||||
if value.startswith('BUG_PRIVATE'):
|
||||
self.assertNotIn(value, serialized)
|
||||
for decision in ('accepted', 'rejected', 'duplicate'):
|
||||
if decision != 'accepted':
|
||||
report = self.submit(**dict(private, title='BUG_PRIVATE_TITLE_MARKER ' + decision))
|
||||
self.review(report['id'], decision=decision, reward_rep=20 if decision == 'accepted' else 0,
|
||||
reason='BUG_PRIVATE_REVIEW_MARKER: independently reviewed sensitive evidence.')
|
||||
for uid in (1, 2, 3, 5):
|
||||
self.assertTrue(all(item['kind'] == 'activity' for item in self.state(uid)['activities']))
|
||||
for uid in (3, 5, 8):
|
||||
serialized = json.dumps(self.state(uid), ensure_ascii=False)
|
||||
for marker in ('BUG_PRIVATE_TITLE_MARKER', 'BUG_PRIVATE_BODY_MARKER',
|
||||
'BUG_PRIVATE_PROOF_MARKER', 'BUG_PRIVATE_REVIEW_MARKER'):
|
||||
self.assertNotIn(marker, serialized)
|
||||
self.assertEqual(len(self.state(2)['own_submissions']), 3)
|
||||
self.assertEqual(self.state(2)['activities'], [])
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 20)
|
||||
|
||||
def test_unknown_user_and_invalid_uid_cannot_read_or_submit_even_if_listed_admin(self):
|
||||
self.assert_error(403, 'not_registered', lambda: board.snapshot(self.db, 99, (99,)))
|
||||
self.assert_error(403, 'not_registered',
|
||||
lambda: board.act(self.db, 99, self.submission_body(), (99,)))
|
||||
for uid in (True, False, 0, -1, '2', 2.0, 2**53):
|
||||
with self.subTest(uid=uid):
|
||||
self.assert_error(400, 'invalid_user', lambda: self.state(uid))
|
||||
self.assert_error(400, 'invalid_user', lambda: self.submit(uid=uid))
|
||||
self.assertEqual(self.count('community_board_submissions'), 0)
|
||||
|
||||
def test_banned_or_api_blocked_actor_is_denied_for_snapshot_submit_and_replay(self):
|
||||
body = self.submission_body(request_id='stable-before-user-block')
|
||||
result = board.act(self.db, 2, body, self.admins)
|
||||
for flag in ('banned', 'api_blocked'):
|
||||
for value in (1, None, 'unknown'):
|
||||
with self.subTest(flag=flag, value=value):
|
||||
self.execute('UPDATE users SET ' + flag + '=? WHERE tg_id=2', (value,))
|
||||
self.assert_error(403, 'blocked', lambda: self.state(2))
|
||||
self.assert_error(403, 'blocked', lambda: self.submit(2), operation_rejected=False)
|
||||
self.assert_error(403, 'blocked', lambda: board.act(self.db, 2, body, self.admins),
|
||||
operation_rejected=False)
|
||||
self.execute('UPDATE users SET ' + flag + '=0 WHERE tg_id=2')
|
||||
self.assertEqual(board.act(self.db, 2, body, self.admins), result)
|
||||
self.assertEqual(self.count('community_board_submissions'), 1)
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
|
||||
def test_blocked_author_can_be_rejected_or_duplicated_but_not_rewarded(self):
|
||||
# admin can still reject or mark-duplicate (clearing the item) and accept with
|
||||
# zero reward, but reputation is never credited to a blocked account and an
|
||||
# accept-with-reward is refused terminally so the admin picks another action.
|
||||
for flag in ('banned', 'api_blocked'):
|
||||
for decision in ('rejected', 'duplicate'):
|
||||
report = self.submit(request_id=f'blocked-{flag}-{decision}-clear')
|
||||
self.execute('UPDATE users SET ' + flag + '=1 WHERE tg_id=2')
|
||||
result = self.review(report['id'], decision=decision, reward_rep=0)
|
||||
self.assertEqual(result['status'], decision)
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.execute('UPDATE users SET ' + flag + '=0 WHERE tg_id=2')
|
||||
report = self.submit(request_id=f'blocked-{flag}-accept')
|
||||
self.execute('UPDATE users SET ' + flag + '=1 WHERE tg_id=2')
|
||||
self.assert_error(409, 'author_ineligible',
|
||||
lambda: self.review(report['id'], decision='accepted', reward_rep=10),
|
||||
operation_rejected=True)
|
||||
zero = self.review(report['id'], decision='accepted', reward_rep=0)
|
||||
self.assertEqual((zero['status'], zero['reward_rep']), ('accepted', 0))
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.execute('UPDATE users SET ' + flag + '=0 WHERE tg_id=2')
|
||||
|
||||
def test_blocked_admin_cannot_review(self):
|
||||
report = self.submit()
|
||||
for flag in ('banned', 'api_blocked'):
|
||||
self.execute('UPDATE users SET ' + flag + '=1 WHERE tg_id=1')
|
||||
self.assert_error(403, 'blocked', lambda: self.review(report['id']), operation_rejected=False)
|
||||
self.execute('UPDATE users SET ' + flag + '=0 WHERE tg_id=1')
|
||||
self.assertEqual(self.state(2)['own_submissions'][0]['status'], 'pending')
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
|
||||
def test_review_is_admin_only_and_body_cannot_grant_admin_authority(self):
|
||||
report = self.submit(kind='bug', category='critical')
|
||||
for uid in (2, 3, 5):
|
||||
for submission_id in (report['id'], 999999):
|
||||
self.assert_error(403, 'admin_only', lambda: self.review(submission_id, uid=uid),
|
||||
operation_rejected=True)
|
||||
forged = self.submission_body(is_admin=True, admins=[2], reward_rep=40)
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, forged, self.admins),
|
||||
operation_rejected=True)
|
||||
self.assertFalse(self.state(2, admins=(True, '2'))['is_admin'])
|
||||
self.assertEqual(self.state(2, admins=(True, '2'))['review_queue'], [])
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
|
||||
def test_admin_cannot_review_or_award_own_submission(self):
|
||||
report = self.submit(uid=1)
|
||||
for decision in ('accepted', 'rejected', 'duplicate'):
|
||||
self.assert_error(403, 'self_review',
|
||||
lambda: self.review(report['id'], decision=decision,
|
||||
reward_rep=40 if decision == 'accepted' else 0),
|
||||
operation_rejected=True)
|
||||
self.assertEqual(self.rep(1), self.BASE_REP)
|
||||
self.review(report['id'], uid=4, reward_rep=12)
|
||||
self.assertEqual(self.rep(1), self.BASE_REP + 12)
|
||||
self.assertEqual(self.rep(4), self.BASE_REP)
|
||||
|
||||
def test_accept_is_atomic_with_unique_audit_and_never_changes_money_or_coins(self):
|
||||
balances = self.rows('SELECT tg_id,legacy_balance,points FROM users ORDER BY tg_id')
|
||||
wallets = self.rows('SELECT * FROM community_wallets ORDER BY uid')
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], reward_rep=40, request_id='audit-accept-once-0001')
|
||||
result = board.act(self.db, 1, body, self.admins)
|
||||
self.assertEqual(result, {'ok': True, 'action': 'review', 'id': report['id'],
|
||||
'status': 'accepted', 'reward_rep': 40, 'author_uid': 2})
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 40)
|
||||
self.assertEqual(self.rep(1), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
audit = self.rows('SELECT submission_id,actor_uid,author_uid,decision,reward_rep,reason,request_id,digest,created_at '
|
||||
'FROM community_board_reviews')[0]
|
||||
expected_digest = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False,
|
||||
separators=(',', ':'), allow_nan=False).encode('utf-8')).hexdigest()
|
||||
self.assertEqual(audit, (report['id'], 1, 2, 'accepted', 40, body['reason'], body['request_id'],
|
||||
expected_digest, self.NOW))
|
||||
self.assertEqual(self.rows('SELECT tg_id,legacy_balance,points FROM users ORDER BY tg_id'), balances)
|
||||
self.assertEqual(self.rows('SELECT * FROM community_wallets ORDER BY uid'), wallets)
|
||||
for decision in ('accepted', 'rejected', 'duplicate'):
|
||||
self.assert_error(409, 'already_reviewed',
|
||||
lambda: self.review(report['id'], uid=4, decision=decision,
|
||||
reward_rep=40 if decision == 'accepted' else 0))
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 40)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
def test_rejected_duplicate_and_zero_reward_accept_are_terminal_without_award(self):
|
||||
for decision in ('rejected', 'duplicate', 'accepted'):
|
||||
report = self.submit()
|
||||
result = self.review(report['id'], decision=decision, reward_rep=0)
|
||||
self.assertEqual((result['status'], result['reward_rep']), (decision, 0))
|
||||
self.assert_error(409, 'already_reviewed', lambda: self.review(report['id'], reward_rep=20))
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 3)
|
||||
self.assertEqual([row[0] for row in self.rows('SELECT reward_rep FROM community_board_reviews')], [0, 0, 0])
|
||||
|
||||
def test_submit_and_review_replays_are_exact_and_key_order_independent(self):
|
||||
submit_body = self.submission_body(request_id='same-submit-replay-0001')
|
||||
report = board.act(self.db, 2, submit_body, self.admins)
|
||||
for _ in range(3):
|
||||
reverse = dict(reversed(list(submit_body.items())))
|
||||
self.assertEqual(board.act(self.db, 2, reverse, self.admins), report)
|
||||
review_body = self.review_body(report['id'], reward_rep=15, request_id='same-review-replay-0001')
|
||||
result = board.act(self.db, 1, review_body, self.admins)
|
||||
for _ in range(3):
|
||||
self.assertEqual(board.act(self.db, 1, review_body, self.admins), result)
|
||||
self.assertEqual(self.count('community_board_submissions'), 1)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 15)
|
||||
|
||||
def test_request_id_is_scoped_to_uid_but_conflicts_for_any_changed_body(self):
|
||||
body = self.submission_body(request_id='same-uid-scoped-request')
|
||||
first = board.act(self.db, 2, body, self.admins)
|
||||
second = board.act(self.db, 3, body, self.admins)
|
||||
self.assertNotEqual(first['id'], second['id'])
|
||||
for change in ({'title': 'Changed title for request'}, {'proof': body['proof'] + ' '},
|
||||
{'kind': 'bug', 'category': 'low'}, {'action': 'review'}, {'unknown': 1}):
|
||||
self.assert_error(409, 'request_conflict',
|
||||
lambda: board.act(self.db, 2, dict(body, **change), self.admins),
|
||||
operation_rejected=False)
|
||||
review_body = self.review_body(first['id'], request_id='stable-review-conflict')
|
||||
board.act(self.db, 1, review_body, self.admins)
|
||||
for change in ({'id': second['id']}, {'reward_rep': 20}, {'decision': 'duplicate', 'reward_rep': 0},
|
||||
{'reason': review_body['reason'] + ' '}):
|
||||
self.assert_error(409, 'request_conflict',
|
||||
lambda: board.act(self.db, 1, dict(review_body, **change), self.admins),
|
||||
operation_rejected=False)
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 10)
|
||||
self.assertEqual(self.rep(3), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
def test_replay_rechecks_admin_authority_and_actor_block_before_receipt(self):
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], request_id='review-before-role-change')
|
||||
result = board.act(self.db, 1, body, self.admins)
|
||||
self.assert_error(403, 'admin_only', lambda: board.act(self.db, 1, body, (4,)),
|
||||
operation_rejected=False)
|
||||
self.execute('UPDATE users SET api_blocked=1 WHERE tg_id=1')
|
||||
self.assert_error(403, 'blocked', lambda: board.act(self.db, 1, body, self.admins),
|
||||
operation_rejected=False)
|
||||
self.execute('UPDATE users SET api_blocked=0 WHERE tg_id=1')
|
||||
self.assertEqual(board.act(self.db, 1, body, self.admins), result)
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 10)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
def test_concurrent_approval_has_one_winner_and_exactly_one_award(self):
|
||||
report = self.submit()
|
||||
bodies = [self.review_body(report['id'], reward_rep=40) for _ in range(8)]
|
||||
barrier = threading.Barrier(len(bodies))
|
||||
|
||||
def attempt(index):
|
||||
barrier.wait(timeout=10)
|
||||
try:
|
||||
return board.act(self.db, 1 if index % 2 else 4, bodies[index], self.admins)
|
||||
except board.BoardError as error:
|
||||
return error.status, error.code
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(bodies)) as pool:
|
||||
results = list(pool.map(attempt, range(len(bodies))))
|
||||
successes = [result for result in results if isinstance(result, dict)]
|
||||
self.assertEqual(len(successes), 1)
|
||||
self.assertEqual([result for result in results if isinstance(result, tuple)],
|
||||
[(409, 'already_reviewed')] * (len(bodies) - 1))
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 40)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
|
||||
def test_concurrent_same_request_returns_one_saved_receipt_to_all_callers(self):
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], reward_rep=17, request_id='concurrent-same-receipt')
|
||||
barrier = threading.Barrier(8)
|
||||
|
||||
def attempt(_):
|
||||
barrier.wait(timeout=10)
|
||||
return board.act(self.db, 1, body, self.admins)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(attempt, range(8)))
|
||||
self.assertTrue(all(result == results[0] for result in results))
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 17)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
|
||||
def test_concurrent_conflicting_receipts_do_not_apply_both_bodies(self):
|
||||
report = self.submit()
|
||||
bodies = [self.review_body(report['id'], reward_rep=reward, request_id='concurrent-conflict-id')
|
||||
for reward in (10, 20)]
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def attempt(body):
|
||||
barrier.wait(timeout=10)
|
||||
try:
|
||||
return board.act(self.db, 1, body, self.admins)
|
||||
except board.BoardError as error:
|
||||
return error.status, error.code
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(attempt, bodies))
|
||||
accepted = [result for result in results if isinstance(result, dict)]
|
||||
self.assertEqual(len(accepted), 1)
|
||||
self.assertIn((409, 'request_conflict'), results)
|
||||
self.assertEqual(self.rep(), self.BASE_REP + accepted[0]['reward_rep'])
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
def test_failure_in_audit_insert_rolls_back_status_rep_and_receipt(self):
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], request_id='audit-failure-can-retry')
|
||||
self.execute("CREATE TRIGGER board_test_fail_audit BEFORE INSERT ON community_board_reviews "
|
||||
"BEGIN SELECT RAISE(ABORT,'simulated audit failure'); END")
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
board.act(self.db, 1, body, self.admins)
|
||||
self.assertEqual(self.state()['own_submissions'][0]['status'], 'pending')
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
self.assertEqual(self.count('community_board_operations'), 1)
|
||||
self.execute('DROP TRIGGER board_test_fail_audit')
|
||||
self.assertEqual(board.act(self.db, 1, body, self.admins)['status'], 'accepted')
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 10)
|
||||
|
||||
def test_failure_saving_receipt_rolls_back_audit_status_and_rep_together(self):
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], request_id='receipt-failure-can-retry')
|
||||
self.execute("CREATE TRIGGER board_test_fail_receipt BEFORE INSERT ON community_board_operations "
|
||||
"WHEN NEW.actor_uid=1 BEGIN SELECT RAISE(ABORT,'simulated receipt failure'); END")
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
board.act(self.db, 1, body, self.admins)
|
||||
self.assertEqual(self.state()['own_submissions'][0]['status'], 'pending')
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
self.assertEqual(self.count('community_board_operations'), 1)
|
||||
self.execute('DROP TRIGGER board_test_fail_receipt')
|
||||
board.act(self.db, 1, body, self.admins)
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 10)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
def test_review_audit_receipt_and_terminal_submission_are_immutable(self):
|
||||
report = self.submit()
|
||||
self.review(report['id'], reward_rep=10)
|
||||
statements = [
|
||||
'UPDATE community_board_reviews SET reward_rep=40',
|
||||
'DELETE FROM community_board_reviews',
|
||||
"UPDATE community_board_operations SET result='{}'",
|
||||
'DELETE FROM community_board_operations',
|
||||
"UPDATE community_board_submissions SET status='pending'",
|
||||
'DELETE FROM community_board_submissions',
|
||||
'INSERT OR REPLACE INTO community_board_reviews SELECT * FROM community_board_reviews',
|
||||
'INSERT OR REPLACE INTO community_board_operations SELECT * FROM community_board_operations',
|
||||
'INSERT OR REPLACE INTO community_board_submissions SELECT * FROM community_board_submissions',
|
||||
]
|
||||
for statement in statements:
|
||||
with self.subTest(statement=statement):
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
con.execute(statement)
|
||||
con.rollback()
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 10)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
|
||||
def test_pending_limit_is_atomic_and_failed_attempt_can_retry_after_review(self):
|
||||
for _ in range(board.MAX_PENDING):
|
||||
self.submit()
|
||||
body = self.submission_body(request_id='retry-after-pending-limit')
|
||||
self.assert_error(409, 'pending_limit', lambda: board.act(self.db, 2, body, self.admins),
|
||||
operation_rejected=True)
|
||||
self.assertEqual(self.count('community_board_operations'), board.MAX_PENDING)
|
||||
oldest = self.rows('SELECT MIN(id) FROM community_board_submissions')[0][0]
|
||||
self.review(oldest, decision='duplicate', reward_rep=0)
|
||||
board.act(self.db, 2, body, self.admins)
|
||||
self.assertEqual(sum(item['status'] == 'pending' for item in self.state()['own_submissions']),
|
||||
board.MAX_PENDING)
|
||||
|
||||
def test_concurrent_submissions_cannot_exceed_pending_limit(self):
|
||||
bodies = [self.submission_body() for _ in range(8)]
|
||||
barrier = threading.Barrier(len(bodies))
|
||||
|
||||
def attempt(body):
|
||||
barrier.wait(timeout=10)
|
||||
try:
|
||||
return board.act(self.db, 2, body, self.admins)
|
||||
except board.BoardError as error:
|
||||
return error.status, error.code
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(bodies)) as pool:
|
||||
results = list(pool.map(attempt, bodies))
|
||||
self.assertEqual(sum(isinstance(result, dict) for result in results), board.MAX_PENDING)
|
||||
self.assertEqual(sum(result == (409, 'pending_limit') for result in results), 8 - board.MAX_PENDING)
|
||||
self.assertEqual(self.count('community_board_submissions'), board.MAX_PENDING)
|
||||
self.assertEqual(self.count('community_board_operations'), board.MAX_PENDING)
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
|
||||
def test_daily_limit_counts_reviewed_and_duplicate_submissions_and_resets_at_utc_midnight(self):
|
||||
day_start = self.NOW // 86_400 * 86_400
|
||||
self.clock.return_value = day_start + 86_399
|
||||
for _ in range(board.DAILY_SUBMISSION_LIMIT):
|
||||
report = self.submit()
|
||||
self.review(report['id'], decision='duplicate', reward_rep=0)
|
||||
body = self.submission_body(request_id='retry-after-utc-midnight')
|
||||
self.assert_error(429, 'submission_day_limit', lambda: board.act(self.db, 2, body, self.admins),
|
||||
operation_rejected=True)
|
||||
self.assertEqual(self.count('community_board_submissions'), board.DAILY_SUBMISSION_LIMIT)
|
||||
self.clock.return_value = day_start + 86_400
|
||||
board.act(self.db, 2, body, self.admins)
|
||||
self.assertEqual(self.count('community_board_submissions'), board.DAILY_SUBMISSION_LIMIT + 1)
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
|
||||
def test_all_categories_are_validated_and_arbitrary_kind_or_category_is_rejected(self):
|
||||
for category in board.ACTIVITY_CATEGORIES:
|
||||
report = self.submit(category=category)
|
||||
self.review(report['id'], decision='rejected', reward_rep=0)
|
||||
for category in board.BUG_SEVERITIES:
|
||||
report = self.submit(kind='bug', category=category)
|
||||
self.review(report['id'], decision='rejected', reward_rep=0)
|
||||
for kind in ('cash', '', None, True, [], {}):
|
||||
self.assert_error(400, 'invalid_kind', lambda: self.submit(kind=kind))
|
||||
for kind, category in (('activity', 'critical'), ('bug', 'docs'), ('activity', 'other'),
|
||||
('bug', ''), ('bug', None), ('activity', [])):
|
||||
self.assert_error(400, 'invalid_category', lambda: self.submit(kind=kind, category=category))
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
|
||||
def test_text_bounds_control_characters_and_non_text_values_are_rejected_without_writes(self):
|
||||
for field in ('title', 'description', 'proof'):
|
||||
minimum, maximum = board.TEXT_LIMITS[field]
|
||||
invalid_values = (None, 12, True, [], 'x' * (minimum - 1), 'x' * (maximum + 1),
|
||||
' ' * (maximum + 1) + 'valid minimum length text',
|
||||
'valid long enough text with bad control\x00 suffix')
|
||||
for value in invalid_values:
|
||||
with self.subTest(field=field, value_type=type(value).__name__):
|
||||
self.assert_error(400, 'invalid_' + field,
|
||||
lambda: self.submit(**{field: value}), operation_rejected=True)
|
||||
self.assertEqual(self.count('community_board_submissions'), 0)
|
||||
self.assertEqual(self.count('community_board_operations'), 0)
|
||||
|
||||
def test_boundary_lengths_are_accepted_and_text_is_trimmed_not_interpreted(self):
|
||||
result = self.submit(title='t' * 160, description='d' * 6_000, proof='p' * 2_000)
|
||||
own = self.state()['own_submissions'][0]
|
||||
self.assertEqual((len(own['title']), len(own['description']), len(own['proof'])), (160, 6_000, 2_000))
|
||||
self.review(result['id'], reason='r' * 1_000, reward_rep=40)
|
||||
other = self.submit(title=' Trimmed title ', description=' ' + 'd' * 30 + ' ', proof=' proof ')
|
||||
item = next(row for row in self.state()['own_submissions'] if row['id'] == other['id'])
|
||||
self.assertEqual((item['title'], item['description'], item['proof']), ('Trimmed title', 'd' * 30, 'proof'))
|
||||
|
||||
def test_review_requires_reason_valid_decision_bounded_integer_reward_and_id(self):
|
||||
report = self.submit()
|
||||
for reward in (-1, 41, True, False, 1.0, '10', None, [], {}):
|
||||
self.assert_error(400, 'invalid_reward_rep', lambda: self.review(report['id'], reward_rep=reward))
|
||||
for decision in ('rejected', 'duplicate'):
|
||||
self.assert_error(400, 'invalid_reward_rep',
|
||||
lambda: self.review(report['id'], decision=decision, reward_rep=1))
|
||||
for reason in ('', ' ', 'tiny', 'x' * 1_001, None, 5, 'unsafe\x01reason'):
|
||||
self.assert_error(400, 'invalid_reason', lambda: self.review(report['id'], reason=reason))
|
||||
for decision in ('accept', 'reject', 'paid', None, True, [], {}):
|
||||
self.assert_error(400, 'invalid_decision', lambda: self.review(report['id'], decision=decision))
|
||||
for submission_id in (True, False, 0, -1, 1.0, '1', 2**53):
|
||||
self.assert_error(400, 'invalid_id', lambda: self.review(submission_id))
|
||||
self.assert_error(404, 'submission_not_found', lambda: self.review(999999))
|
||||
self.assertEqual(self.state()['own_submissions'][0]['status'], 'pending')
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
|
||||
def test_invalid_envelope_unknown_action_and_client_controlled_fields_are_rejected(self):
|
||||
for body in (None, [], 'submit', 1, True):
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, body, self.admins))
|
||||
for request_id in (None, '', 'short', 'x' * 97, 'spaces are invalid', 'request/with/slashes', 123):
|
||||
self.assert_error(400, 'request_id_required', lambda: self.submit(request_id=request_id))
|
||||
missing = self.submission_body()
|
||||
del missing['proof']
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, missing, self.admins),
|
||||
operation_rejected=True)
|
||||
for changes in ({'reward_rep': 40}, {'author_uid': 1}, {'status': 'accepted'},
|
||||
{'amount': 100}, {'cash_bounty': True}):
|
||||
self.assert_error(400, 'invalid_body', lambda: self.submit(**changes), operation_rejected=True)
|
||||
for action in ('messages', 'grant', 'topup', 'delete', '', None, []):
|
||||
self.assert_error(400, 'unknown_action', lambda: self.submit(action=action), operation_rejected=True)
|
||||
huge = self.submission_body(description='a' * (board.MAX_REQUEST_BYTES + 1))
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, huge, self.admins))
|
||||
non_json = self.submission_body(description=float('nan'))
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, non_json, self.admins))
|
||||
malformed_unicode = self.submission_body(description='bad surrogate \ud800')
|
||||
self.assert_error(400, 'invalid_body', lambda: board.act(self.db, 2, malformed_unicode, self.admins))
|
||||
self.assertEqual(self.count('community_board_submissions'), 0)
|
||||
self.assertEqual(self.rep(), self.BASE_REP)
|
||||
|
||||
def test_recognizable_credentials_are_rejected_and_not_echoed_but_redacted_proof_is_allowed(self):
|
||||
credentials = ['Bearer ' + 'a' * 32, 'sk-' + 'x' * 32, 'ghp_' + 'x' * 30,
|
||||
'api_key=' + 'x' * 32, '123456789:' + 'x' * 35,
|
||||
'-' * 5 + 'BEGIN ' + 'PRIVATE KEY' + '-' * 5]
|
||||
for credential in credentials:
|
||||
body = self.submission_body(kind='bug', category='high', proof=credential)
|
||||
error = self.assert_error(400, 'secrets_not_allowed',
|
||||
lambda: board.act(self.db, 2, body, self.admins),
|
||||
operation_rejected=True)
|
||||
self.assertNotIn(credential, error.message)
|
||||
self.assertEqual(self.count('community_board_submissions'), 0)
|
||||
self.assertEqual(self.count('community_board_operations'), 0)
|
||||
self.submit(kind='bug', category='low',
|
||||
proof='Authorization: Bearer [REDACTED], api_key=[REDACTED]; request_id safe-proof-123')
|
||||
self.assertEqual(self.count('community_board_submissions'), 1)
|
||||
|
||||
def test_xss_is_plain_data_and_sql_payload_never_executes(self):
|
||||
title = '<img src=x onerror="window.boardXSS=1">'
|
||||
description = '<script>window.boardXSS=2</script> Expected text, actual text, reproducible result.'
|
||||
proof = "'); UPDATE users SET rep=9999; DROP TABLE users; --"
|
||||
reason = '<svg onload="window.boardXSS=3">Independent review as plain text.</svg>'
|
||||
report = self.submit(title=title, description=description, proof=proof)
|
||||
self.review(report['id'], reward_rep=9, reason=reason)
|
||||
item = self.state(3)['activities'][0]
|
||||
self.assertEqual((item['title'], item['description'], item['proof'], item['review_reason']),
|
||||
(title, description, proof, reason))
|
||||
self.assertEqual(json.loads(json.dumps(item)), item)
|
||||
self.assertEqual(self.rows('SELECT COUNT(*) FROM users'), [(8,)])
|
||||
self.assertEqual(self.rep(), self.BASE_REP + 9)
|
||||
self.assertEqual(self.rep(3), self.BASE_REP)
|
||||
self.assertNotIn('html', item)
|
||||
# This is a raw JSON API: the frontend integration must escape these four fields.
|
||||
|
||||
def test_restart_is_additive_and_keeps_receipts_audits_and_existing_balances(self):
|
||||
report = self.submit()
|
||||
body = self.review_body(report['id'], reward_rep=8, request_id='restart-survives-receipt')
|
||||
result = board.act(self.db, 1, body, self.admins)
|
||||
before_users = self.rows('SELECT * FROM users ORDER BY tg_id')
|
||||
before_wallets = self.rows('SELECT * FROM community_wallets ORDER BY uid')
|
||||
for _ in range(3):
|
||||
board.init_db(self.db)
|
||||
self.assertEqual(board.act(self.db, 1, body, self.admins), result)
|
||||
self.assertEqual(self.rows('SELECT * FROM users ORDER BY tg_id'), before_users)
|
||||
self.assertEqual(self.rows('SELECT * FROM community_wallets ORDER BY uid'), before_wallets)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
self.assertEqual(self.count('community_board_operations'), 2)
|
||||
|
||||
def test_missing_access_control_columns_fail_closed_without_creating_user_schema(self):
|
||||
bad_db = Path(self.tmp.name) / 'incomplete.db'
|
||||
with closing(sqlite3.connect(bad_db)) as con:
|
||||
con.execute('CREATE TABLE users(tg_id INTEGER PRIMARY KEY,rep INTEGER DEFAULT 0)')
|
||||
con.execute('INSERT INTO users(tg_id) VALUES(2)')
|
||||
con.commit()
|
||||
board.init_db(bad_db)
|
||||
self.assert_error(503, 'board_unavailable', lambda: board.snapshot(bad_db, 2, self.admins))
|
||||
self.assert_error(503, 'board_unavailable',
|
||||
lambda: board.act(bad_db, 2, self.submission_body(), self.admins),
|
||||
operation_rejected=False)
|
||||
with closing(sqlite3.connect(bad_db)) as con:
|
||||
columns = {row[1] for row in con.execute('PRAGMA table_info(users)')}
|
||||
self.assertEqual(columns, {'tg_id', 'rep'})
|
||||
self.assertEqual(con.execute('SELECT COUNT(*) FROM community_board_operations').fetchone()[0], 0)
|
||||
|
||||
def test_null_reputation_can_be_awarded_but_corrupt_reputation_is_not_coerced(self):
|
||||
self.execute('UPDATE users SET rep=NULL WHERE tg_id=2')
|
||||
self.assertEqual(self.state()['reputation'], 0)
|
||||
report = self.submit()
|
||||
self.review(report['id'], reward_rep=6)
|
||||
self.assertEqual(self.rep(), 6)
|
||||
self.execute("UPDATE users SET rep='corrupt' WHERE tg_id=2")
|
||||
self.assert_error(503, 'board_unavailable', lambda: self.state())
|
||||
self.assert_error(503, 'board_unavailable', lambda: self.submit(), operation_rejected=False)
|
||||
self.assertEqual(self.rep(), 'corrupt')
|
||||
|
||||
def test_reputation_overflow_fails_without_rounding_or_issuing_reward(self):
|
||||
self.execute('UPDATE users SET rep=? WHERE tg_id=2', (2**63 - 1,))
|
||||
report = self.submit()
|
||||
self.assert_error(409, 'reputation_limit', lambda: self.review(report['id'], reward_rep=1),
|
||||
operation_rejected=True)
|
||||
self.assertEqual(self.rep(), 2**63 - 1)
|
||||
self.assertEqual(self.state()['own_submissions'][0]['status'], 'pending')
|
||||
self.assertEqual(self.count('community_board_reviews'), 0)
|
||||
self.review(report['id'], reward_rep=0)
|
||||
self.assertEqual(self.rep(), 2**63 - 1)
|
||||
self.assertEqual(self.count('community_board_reviews'), 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,358 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import vm from 'node:vm';
|
||||
import {readFileSync} from 'node:fs';
|
||||
|
||||
// Parent may target the assembled bot/webapp/static/index.html without copying fixtures.
|
||||
const html=readFileSync(process.env.IISHKO_UI_HTML||new URL('../bot/webapp/static/index.html',import.meta.url),'utf8');
|
||||
const scripts=[...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)].map(match=>match[1]).filter(source=>source.trim());
|
||||
const main=scripts.find(source=>source.includes('/* Contest UI: begin.'));
|
||||
assert.ok(main,'contest additions must live in the real application HTML');
|
||||
const between=(source,start,end)=>{
|
||||
const from=source.indexOf(start),to=source.indexOf(end,from+start.length);
|
||||
assert.ok(from>=0&&to>from,`missing source anchors: ${start} / ${end}`);
|
||||
return source.slice(from,to);
|
||||
};
|
||||
const helpers=scripts.find(source=>source.includes('const MiniAppFlows='));
|
||||
const values=between(main,'const esc=v=>','function haptic(');
|
||||
const contest=between(main,'/* Contest UI: begin.','/* Contest UI: end.');
|
||||
const keySource=between(main,'/* Keys are managed only here;','/* ---------- [V3] экономика');
|
||||
const usageSource=between(main,'const ECON_PERIODS=','function econUsageResults(');
|
||||
const profileSource=between(main,'function profile(','/* Keys are managed only here;');
|
||||
const modelSource=between(main,'function modelCard(','function modelsFiltered(');
|
||||
let nextId=0;
|
||||
const plain=value=>JSON.parse(JSON.stringify(value));
|
||||
|
||||
function harness(store=new Map()){
|
||||
const elements=new Map(),listeners=new Map(),posts=[],gets=[],copies=[],notices=[],confirms=[],focus=[];
|
||||
let renders=0;
|
||||
const document={visibilityState:'visible',activeElement:null,addEventListener(name,fn){const list=listeners.get(name)||[];list.push(fn);listeners.set(name,list)},querySelector:selector=>get(selector),querySelectorAll:()=>[]};
|
||||
class Element{
|
||||
constructor(selector){this.selector=selector;this.id=selector.replace(/^#/,'');this.dataset={};this.attributes={};this.listeners=new Map();this.innerHTML='';this.textContent='';this.value='';this.disabled=false;this.open=false;this.isConnected=true;this.fields=[];this.readOnly=false;this.style={};}
|
||||
addEventListener(name,fn){const list=this.listeners.get(name)||[];list.push(fn);this.listeners.set(name,list);}
|
||||
removeEventListener(){}
|
||||
setAttribute(name,value){this.attributes[name]=String(value);}
|
||||
getAttribute(name){return this.attributes[name]??null;}
|
||||
showModal(){this.open=true;}
|
||||
close(){if(!this.open)return;this.open=false;for(const fn of this.listeners.get('close')||[])fn({target:this});}
|
||||
focus(){document.activeElement=this;focus.push(this.selector);}
|
||||
select(){this.selected=true;}
|
||||
querySelector(selector){return /input|select|textarea/.test(selector)&&/<(?:input|select|textarea)\b/.test(this.innerHTML)?get('#first-field'):null;}
|
||||
querySelectorAll(){return [];}
|
||||
closest(selector){return [...selector.matchAll(/\[data-([a-z-]+)\]/g)].some(match=>Object.hasOwn(this.dataset,match[1].replace(/-([a-z])/g,(_,letter)=>letter.toUpperCase())))?this:null;}
|
||||
reportValidity(){return this.valid!==false;}
|
||||
}
|
||||
function get(selector){if(!elements.has(selector))elements.set(selector,new Element(selector));return elements.get(selector);}
|
||||
document.activeElement=get('#trigger');
|
||||
const c=vm.createContext({console,Map,Set,Number,JSON,String,Math,Date,URL,URLSearchParams,Uint8Array,encodeURIComponent,
|
||||
localStorage:{getItem:key=>store.get(key)||null,setItem:(key,value)=>store.set(key,String(value)),removeItem:key=>store.delete(key)},
|
||||
crypto:{randomUUID:()=>`contest-vm-request-${String(++nextId).padStart(6,'0')}`},
|
||||
FormData:class{constructor(form){return form.fields[Symbol.iterator]();}},
|
||||
document,window:{addEventListener(){}},performance:{now:()=>100},setTimeout,clearTimeout,setInterval:()=>1,clearInterval(){},
|
||||
$:get,resolvedUid:'123',current:'activities',tg:null,navigator:{clipboard:{writeText:async value=>{copies.push(value);}}},location:{hash:'#keys'},
|
||||
intro:(title,text)=>`<header><h1>${title}</h1><p>${text}</p></header>`,empty:(title,text)=>`<h2>${title}</h2><p>${text}</p>`,
|
||||
haptic:()=>{},popup:(...args)=>notices.push(args),bust:()=>{},render:async()=>{renders++;},
|
||||
icon:()=>'<svg aria-hidden="true"></svg>',
|
||||
askCaptcha:async()=>null,askAmount:async()=>5,askConfirm:async(...args)=>{confirms.push(args);return true;},
|
||||
connectionHelpHtml:()=>'',weeklyBlock:()=>'',progress:()=>'',ranksBlock:()=>'',globalBlock:()=>'',refreshBtn:()=>'',cached:()=>null,
|
||||
modelStatus:()=> 'stale',mMeta:{status_ts:0},STATUS_UI:{stale:['Не проверена','dim']},AG_LABEL:{},
|
||||
publicConnectionField:(label,value)=>`<label>${label}<input value="${String(value).replaceAll('"','"')}"></label>`,modelAgentAction:()=>'',uptimeHtml:()=>'',
|
||||
post:async(path,body)=>{
|
||||
posts.push({path,body:plain(body)});
|
||||
if(path==='keys/transfer')return {ok:true,moved_usd:7};
|
||||
if(body.action==='purchase')return {ok:true,action:body.action,offer_id:body.offer_id,charged_cents:250,expires_at:1800000000};
|
||||
if(body.action==='create_invoice')return {ok:true,action:body.action,invoice:{id:'invoice-one',amount_cents:500,currency:'USD',status:'pending',pay_url:'https://example.org/pay/invoice-one'}};
|
||||
if(body.action==='check_invoice')return {ok:true,action:body.action,invoice:{id:body.invoice_id,amount_cents:500,currency:'USD',status:'pending'},paid:false,credited_cents:0};
|
||||
return {ok:true,action:body.action,id:body.id||7,status:body.decision||'pending',reward_rep:body.reward_rep||0};
|
||||
},
|
||||
apiResponse:null,apiFresh:async path=>{gets.push(path);return c.apiResponse;}
|
||||
});
|
||||
vm.runInContext(helpers,c);
|
||||
vm.runInContext(values,c);
|
||||
vm.runInContext(contest,c);
|
||||
vm.runInContext(usageSource,c);
|
||||
vm.runInContext(keySource,c);
|
||||
vm.runInContext(profileSource,c);
|
||||
vm.runInContext(modelSource,c);
|
||||
const run=source=>vm.runInContext(source,c);
|
||||
const state=(name,data)=>{c.fixture=data;return run(`${name}View(fixture)`);};
|
||||
const emit=async(name,target)=>{for(const fn of listeners.get(name)||[])await fn({target,preventDefault(){}});await Promise.resolve();await Promise.resolve();};
|
||||
const button=dataset=>{const el=new Element('button');el.dataset=dataset;return el;};
|
||||
return {c,run,state,get,store,posts,gets,copies,notices,confirms,focus,button,emit,renders:()=>renders};
|
||||
}
|
||||
const commerce=overrides=>({uid:123,wallet_cents:1000,currency:'USD',payment_enabled:true,offers:[{id:'topup',kind:'wallet_topup',title:'Пополнить кошелёк',price_cents:500},{id:'requests',kind:'extra_requests',title:'Дополнительные запросы',price_cents:250,requests:50},{id:'model-day',kind:'model_pass',title:'Пропуск модели',price_cents:250,model:'sample-model',duration_seconds:86400}],entitlements:{extra_requests:0,models:[],expires_at:null},invoices:[],history:[],...overrides});
|
||||
const board=overrides=>({uid:123,is_admin:false,reputation:4,activities:[],own_submissions:[],review_queue:[],rules:{summary:'Репутация после независимой модерации',rubric:[],submission_guide:{}},...overrides});
|
||||
const item=overrides=>({id:8,kind:'activity',category:'docs',title:'Проверяемая инструкция',description:'Достаточно подробное описание полезного результата.',proof:'https://example.org/proof',status:'accepted',author_uid:456,reward_rep:5,created_at:1790000000,review_reason:'Проверено независимо',...overrides});
|
||||
const validBug=()=>({fields:[['category','high'],['title','Воспроизводимая ошибка'],['description','Окружение и безопасные шаги, ожидаемый и фактический результат.'],['proof','request_example_12345']]});
|
||||
|
||||
test('all real inline scripts compile and contest routes remain discoverable',()=>{
|
||||
for(const [index,source] of scripts.entries())new vm.Script(source,{filename:`index.contest.html:${index}`});
|
||||
assert.match(main,/activities:\['Вклад и баги','activities'\]/);
|
||||
assert.match(html,/data-tab="activities"/);
|
||||
assert.match(html,/data-tab="econ"/);
|
||||
assert.match(html,/id="contestdlg" aria-labelledby="contest-title" aria-describedby="contest-desc"/);
|
||||
assert.match(html,/id="providerdlg" aria-labelledby="provider-title"/);
|
||||
});
|
||||
|
||||
test('aggregate API credit uses all key buckets, never wallet cents or coins',()=>{
|
||||
const h=harness();h.c.data={balance_usd:10,total_balance_usd:17,main_balance_usd:10,extras_balance_usd:5,promo_balance_usd:2,wallet_cents:90000,balance:1234};
|
||||
assert.deepEqual(plain(h.run('contestBalances(data)')),{main:10,extras:5,promo:2,total:17});
|
||||
h.c.data={keys:[{main:true,remain_usd:10},{n:1,remain_usd:5},{promo:true,remain_usd:2}]};
|
||||
assert.equal(h.run('contestBalances(data).total'),17);
|
||||
assert.equal(h.run('contestBalances({balance_usd:10}).total'),null,'main alone is not a confirmed total');
|
||||
assert.equal(h.run('contestBalances({total_balance_usd:null}).total'),null);
|
||||
assert.match(h.run('contestBalanceHtml(data,true)'),/Основной[\s\S]*Дополнительные[\s\S]*Промо/);
|
||||
});
|
||||
|
||||
test('real profile renders aggregate total and escapes account metadata',()=>{
|
||||
const h=harness();h.c.me={uid:123,username:'<svg onload=x>',rank_name:'<img src=x>',balance_usd:10,total_balance_usd:17,main_balance_usd:10,extras_balance_usd:5,promo_balance_usd:2};
|
||||
const view=h.run('profile(me,{},null,null,null)');
|
||||
assert.match(view,/17 долларов API-кредита по всем ключам/);
|
||||
assert.match(view,/<svg onload=x>/);assert.doesNotMatch(view,/<svg onload=x>/);
|
||||
assert.match(view,/Денежный кошелёк и монеты сообщества сюда не входят/);
|
||||
});
|
||||
|
||||
test('real key cards expose return without deleting and keep promo reveal-only',async()=>{
|
||||
const h=harness();h.c.current='keys';h.c.keys={uid:123,cap:4,keys:[{n:0,main:true,status:1,remain_usd:10},{n:1,status:1,remain_usd:7},{n:-1,promo:true,status:1,remain_usd:2}]};
|
||||
const before=plain(h.c.keys),view=h.run('keysView(keys)');
|
||||
assert.match(view,/data-k="back" data-n="1"[^>]*>Вернуть остаток на основной/);
|
||||
assert.doesNotMatch(view,/data-k="back" data-n="(?:0|-1)"/);
|
||||
await h.run('keyAct({dataset:{k:"back",n:"1"}})');
|
||||
assert.equal(h.posts.length,1);assert.equal(h.posts[0].path,'keys/transfer');
|
||||
assert.equal(h.posts[0].body.usd,0);assert.equal(h.posts[0].body.dir,'from');assert.ok(h.posts[0].body.request_id);
|
||||
assert.deepEqual(plain(h.c.keys),before,'client never removes the extra key');
|
||||
assert.match(h.confirms[0][1],/ключ не удаляется/);assert.match(h.notices[0][1],/не удалён/);
|
||||
});
|
||||
|
||||
test('lost non-destructive return replays the identical saved operation',async()=>{
|
||||
const h=harness();h.c.current='keys';h.run('keysView({uid:123,cap:3,keys:[{n:1,remain_usd:7,status:1}]})');
|
||||
h.c.post=async()=>{throw new Error('lost reply');};
|
||||
await h.run('keyAct({dataset:{k:"back",n:"1"}})');
|
||||
const saved=JSON.parse(h.store.get('keys-pending:123'));
|
||||
h.c.post=async(path,body)=>{h.posts.push({path,body:plain(body)});return {ok:true,moved_usd:7};};
|
||||
await h.run('keyAct({dataset:{k:"retry"}})');
|
||||
assert.deepEqual(h.posts[0].body,saved.body);assert.equal(h.posts[0].path,'keys/transfer');assert.equal(h.store.size,0);
|
||||
});
|
||||
|
||||
test('public feed rejects accidental private bugs, unaccepted work and foreign own reports',()=>{
|
||||
const h=harness();const view=h.state('activities',board({activities:[item(),item({id:9,kind:'bug',title:'PRIVATE PUBLIC LEAK'}),item({id:10,status:'pending',title:'PENDING PUBLIC LEAK'})],own_submissions:[item({id:11,kind:'bug',author_uid:999,title:'FOREIGN OWN LEAK'})],review_queue:[item({kind:'bug',title:'ADMIN QUEUE LEAK',status:'pending'})]}));
|
||||
assert.match(view,/Проверяемая инструкция/);
|
||||
for(const secret of ['PRIVATE PUBLIC LEAK','PENDING PUBLIC LEAK','FOREIGN OWN LEAK','ADMIN QUEUE LEAK'])assert.ok(!view.includes(secret));
|
||||
assert.doesNotMatch(view,/data-board-review/);assert.equal(h.run('boardReviewOpen(8)'),false);
|
||||
});
|
||||
|
||||
test('own private report is escaped and cannot create javascript/data links',()=>{
|
||||
const h=harness(),payload='<img src=x onerror=alert(1)> & " \' </textarea>';
|
||||
const view=h.state('activities',board({own_submissions:[item({kind:'bug',author_uid:123,title:payload,description:payload,proof:'javascript:alert(1)',review_reason:payload})],rules:{summary:payload,rubric:[{kind:'activity',label:payload,example:payload,suggested_rep:[1,5]}]}}));
|
||||
assert.match(view,/Приватный баг-репорт · только автор и администрация/);
|
||||
assert.match(view,/<img/);assert.match(view,/&/);assert.match(view,/"/);assert.match(view,/'/);
|
||||
assert.doesNotMatch(view,/<img src=x|href="javascript:|<\/textarea>/);
|
||||
for(const url of ['javascript:alert(1)','data:text/html,bad','https://name:password@example.org/']){h.c.url=url;assert.equal(h.run('contestSafeUrl(url)'),'');}
|
||||
});
|
||||
|
||||
test('private bug form submits real raw fields with a persisted stable id',async()=>{
|
||||
const h=harness();h.state('activities',board());
|
||||
await h.emit('click',h.button({boardKind:'bug'}));
|
||||
assert.equal(h.get('#contestdlg').open,true);assert.match(h.get('#contest-desc').textContent,/В публичную ленту баг не попадёт/);
|
||||
assert.match(h.get('#contest-fields').innerHTML,/name="description" required minlength="30" maxlength="6000"/);
|
||||
const form=validBug();h.c.form=form;const body=h.run('contestFormBody(contestState.operation,form)');
|
||||
h.c.post=async(path,payload)=>{assert.equal(JSON.parse(h.store.get('contest-pending:activities:123')).body.request_id,payload.request_id);h.posts.push({path,body:plain(payload)});return {ok:true,action:'submit',id:7,status:'pending',reward_rep:0};};
|
||||
h.c.body=body;await h.run('contestPerform("activities",body)');
|
||||
assert.equal(h.posts[0].path,'activities/action');assert.equal(h.posts[0].body.kind,'bug');assert.equal(h.posts[0].body.category,'high');
|
||||
assert.equal(h.store.size,0);assert.equal(h.get('#contestdlg').open,false);assert.match(h.run('contestState.notices.activities'),/ждёт модерации/);
|
||||
});
|
||||
|
||||
test('invalid report is blocked before POST and labels focus the editable fields',()=>{
|
||||
const h=harness();h.state('activities',board());h.run('boardOpen("bug")');h.c.form={fields:[['category','high'],['title','bad'],['description','short'],['proof','tiny']]};
|
||||
assert.throws(()=>h.run('contestFormBody(contestState.operation,form)'),/Проверь категорию/);assert.equal(h.posts.length,0);
|
||||
assert.equal(h.focus.at(-1),'#first-field');h.run('contestCloseDialog()');assert.equal(h.focus.at(-1),'#trigger');
|
||||
});
|
||||
|
||||
test('administrator may review another pending report but cannot self-award',async()=>{
|
||||
const h=harness();const view=h.state('activities',board({is_admin:true,review_queue:[item({id:8,kind:'bug',status:'pending'}),item({id:9,author_uid:123,status:'pending'})]}));
|
||||
assert.match(view,/data-board-review="8"/);assert.doesNotMatch(view,/data-board-review="9"/);
|
||||
assert.equal(h.run('boardReviewOpen(9)'),false);assert.equal(h.run('boardReviewOpen(8)'),true);
|
||||
h.c.form={fields:[['decision','duplicate'],['reward_rep','40'],['reason','Повтор уже подтверждённого дефекта']]};
|
||||
const body=h.run('contestFormBody(contestState.operation,form)');assert.equal(body.reward_rep,0);
|
||||
h.c.body=body;await h.run('contestPerform("activities",body)');assert.equal(h.posts[0].body.decision,'duplicate');assert.equal(h.posts[0].body.reward_rep,0);
|
||||
assert.match(h.run('contestState.notices.activities'),/Дубликат/);
|
||||
});
|
||||
|
||||
test('provider unknown/null capability is honest and metadata is escaped',()=>{
|
||||
const h=harness();h.c.data={model:'sample-model',providers:[{id:'opaque-route',name:'<img onerror=x>',available:null,effort:null,effort_levels:['high'],verification:{status:'unverified',method:'<script>untrusted</script>',checked_at:null}}]};
|
||||
const view=h.run('providersHtml(data)');
|
||||
assert.match(view,/Доступность неизвестна/);assert.match(view,/Происхождение не подтверждено/);assert.match(view,/Поддержка effort неизвестна/);
|
||||
assert.match(view,/<img/);assert.match(view,/<script>/);assert.doesNotMatch(view,/<img onerror|Есть метаданные подтверждения|<select/);
|
||||
assert.match(view,/X-Iishko-Provider: opaque-route/);assert.doesNotMatch(view,/X-Iishko-Effort|data-provider-copy-body|provider-body-/);
|
||||
const off=h.run('providersHtml({model:"sample-model",providers:[{id:"route-off",name:"Off",available:true,effort:false,effort_levels:["high"],verification:{status:"verified",method:"operator_probe",checked_at:1790000000}}]})');
|
||||
assert.match(off,/Не поддерживается/);assert.doesNotMatch(off,/provider-body-|<select|X-Iishko-Effort/);
|
||||
assert.match(h.run('providersHtml({model:"sample-model",providers:[]})'),/нет опубликованных провайдеров/);
|
||||
});
|
||||
|
||||
test('provider query uses the exact encoded model id and an accessible live dialog',async()=>{
|
||||
const h=harness();h.c.apiResponse={model:'vendor/sample-model',providers:[]};
|
||||
assert.equal(await h.run('providerOpen("vendor/sample-model")'),true);
|
||||
assert.equal(h.gets[0],'providers?model=vendor%2Fsample-model');assert.equal(h.get('#providerdlg').open,true);
|
||||
assert.equal(h.get('#provider-content').attributes['aria-busy'],'false');assert.match(h.get('#provider-content').innerHTML,/нет опубликованных/);
|
||||
assert.equal(h.focus.at(-1),'#provider-close');
|
||||
h.get('#providerdlg').close();assert.equal(h.focus.at(-1),'#trigger');
|
||||
});
|
||||
|
||||
test('provider mismatch and transport failure never create a positive verified state',async()=>{
|
||||
const h=harness();h.c.apiResponse={model:'different-model',providers:[]};
|
||||
assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/Метаданные провайдеров не подтверждены/);
|
||||
h.c.apiFresh=async()=>{throw new Error('<svg onload=bad>');};
|
||||
assert.equal(await h.run('providerOpen("sample-model")'),false);assert.match(h.get('#provider-content').innerHTML,/<svg/);assert.doesNotMatch(h.get('#provider-content').innerHTML,/<svg onload/);
|
||||
});
|
||||
|
||||
test('provider effort is a request-body fragment; no X-Iishko-Effort header is ever offered',async()=>{
|
||||
const h=harness();h.c.apiResponse={model:'sample-model',providers:[{id:'route-one',name:'Route',available:true,effort:true,effort_levels:['low','high'],verification:{status:'verified',method:'operator_probe',checked_at:1790000000}}]};
|
||||
await h.run('providerOpen("sample-model")');
|
||||
// Contract is read from the real gateway sources, not from a string oracle:
|
||||
// relay rejects an effort header the body does not carry, registry reads effort from body fields.
|
||||
const relay=readFileSync(new URL('../gateway/gateway_provider_relay.py',import.meta.url),'utf8');
|
||||
const registry=readFileSync(new URL('../gateway/gateway_providers.py',import.meta.url),'utf8');
|
||||
const parser=readFileSync(new URL('../gateway/request_effort.py',import.meta.url),'utf8');
|
||||
const effortFn=registry.slice(registry.indexOf('def response_effort'),registry.indexOf('def safe_to_retry'));
|
||||
assert.match(relay,/headers do not rewrite generation parameters/);
|
||||
assert.match(relay,/X-Iishko-Effort[\s\S]*effort_requires_request_field/);
|
||||
assert.match(registry,/from request_effort import InvalidEffort, read_effort/);
|
||||
assert.match(effortFn,/return read_effort\(payload\)/);
|
||||
assert.match(parser,/"reasoning_effort"/);
|
||||
const view=h.get('#provider-content').innerHTML;
|
||||
assert.doesNotMatch(view,/X-Iishko-Effort/,'the copied example must never suggest an effort header');
|
||||
assert.match(view,/data-provider-copy-body="0"/);assert.match(view,/Фрагмент тела запроса/);
|
||||
assert.equal(h.run('providerSelectEffort(0,"high")'),true);
|
||||
assert.equal(h.get('#provider-example-0').value,'X-Iishko-Provider: route-one','selecting effort must not add a header');
|
||||
const fragment=JSON.parse(h.get('#provider-body-0').value);
|
||||
assert.deepEqual(Object.keys(fragment),['reasoning_effort']);assert.equal(fragment.reasoning_effort,'high');
|
||||
assert.ok(Object.keys(fragment).every(key=>parser.includes('"'+key+'"')),'fragment key must be one the shared gateway parser reads from the request body');
|
||||
assert.equal(h.run('providerSelectEffort(0,"high\\r\\nInjected: value")'),false);
|
||||
assert.equal(h.get('#provider-body-0').value,'{"reasoning_effort": "high"}','rejected value must not reach the fragment');
|
||||
assert.equal(h.run('providerSelectEffort(0,"medium")'),false,'unconfigured level is not selectable');
|
||||
let copyButton=h.c.copyButton=h.button({providerCopy:'0'});await h.emit('click',copyButton);
|
||||
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one']);
|
||||
copyButton=h.c.copyButton=h.button({providerCopyBody:'0'});await h.emit('click',copyButton);
|
||||
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']);
|
||||
assert.equal(await h.run('providerSelectEffort(0,"")'),true);
|
||||
assert.equal(h.get('#provider-body-0').value,'');
|
||||
assert.equal(await h.run('providerCopy(0,copyButton,"body")'),false,'an empty fragment is not copyable');
|
||||
assert.deepEqual(h.copies,['X-Iishko-Provider: route-one','{"reasoning_effort": "high"}']);
|
||||
assert.match(h.run('providersHtml(apiResponse)'),/operator_probe/);
|
||||
});
|
||||
|
||||
test('real model card exposes provider action rather than an API-only feature',()=>{
|
||||
const h=harness();h.c.model={name:'sample-model',available:true,checked_at:0,rank_name:'Участник'};
|
||||
const view=h.run('modelCard(model)');assert.match(view,/data-provider-model="sample-model"/);assert.match(view,/aria-haspopup="dialog"/);assert.match(view,/Провайдеры · effort · проверка/);
|
||||
});
|
||||
|
||||
test('payment disabled keeps topup visible but inert and never invents offers/prices',async()=>{
|
||||
const h=harness();const view=h.state('commerce',commerce({payment_enabled:false,wallet_cents:0}));
|
||||
assert.match(view,/оплата отключена или ещё не настроена/);
|
||||
assert.match(view,/data-commerce="create_invoice"[^>]*disabled/);assert.equal(h.run('commerceOpen("create_invoice","topup")'),false);
|
||||
await h.emit('click',h.button({commerce:'create_invoice',offerId:'topup'}));assert.equal(h.posts.length,0);assert.equal(h.get('#contestdlg').open,false);
|
||||
const empty=h.state('commerce',commerce({payment_enabled:false,offers:[]}));assert.match(empty,/Предложения пока не настроены/);assert.doesNotMatch(empty,/data-commerce=/);
|
||||
});
|
||||
|
||||
test('configured limit/model passes are purchasable from a separate USD-cent wallet',async()=>{
|
||||
const h=harness(),view=h.state('commerce',commerce());h.c.current='econ';
|
||||
assert.match(view,/50 дополнительных запросов/);assert.match(view,/Пропуск на 24 часа: sample-model/);assert.match(view,/\$2\.50 USD/);
|
||||
assert.match(view,/Эти балансы не складываются/);await h.emit('click',h.button({commerce:'purchase',offerId:'requests'}));
|
||||
assert.equal(h.get('#contestdlg').open,true);assert.match(h.get('#contest-desc').textContent,/денежного кошелька/);
|
||||
await h.run('contestPerform("commerce",contestFormBody(contestState.operation,{}))');
|
||||
assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.offer_id,'requests');assert.match(h.run('contestState.notices.commerce'),/Покупка подтверждена/);
|
||||
});
|
||||
|
||||
test('payment metadata/links are escaped and an unsafe pay URL is never clickable',()=>{
|
||||
const h=harness(),view=h.state('commerce',commerce({offers:[{id:'safe-id',kind:'model_pass',title:'<img onerror=x>',price_cents:250,model:'<svg onload=x>'}],invoices:[{id:'invoice-one',status:'pending',amount_cents:500,pay_url:'javascript:alert(1)'}],history:[{delta_cents:-250,kind:'<script>bad</script>',offer_id:'<img>',ts:1790000000}]}));
|
||||
assert.match(view,/<img/);assert.match(view,/<svg/);assert.match(view,/<script>/);assert.doesNotMatch(view,/<img onerror|href="javascript:/);
|
||||
});
|
||||
|
||||
test('unpaid checks complete honestly; a later user check gets a fresh request id',async()=>{
|
||||
const h=harness();h.c.current='econ';h.state('commerce',commerce({invoices:[{id:'invoice-one',status:'pending',amount_cents:500}]}));
|
||||
assert.equal(h.run('commerceOpen("create_invoice","topup")'),false,'never create duplicate invoice while one is open');
|
||||
await h.run('contestPerform("commerce",{action:"check_invoice",invoice_id:"invoice-one"})');
|
||||
assert.match(h.run('contestState.notices.commerce'),/Оплата ещё не подтверждена/);assert.equal(h.store.size,0);
|
||||
await h.run('contestPerform("commerce",{action:"check_invoice",invoice_id:"invoice-one"})');
|
||||
assert.notEqual(h.posts[0].body.request_id,h.posts[1].body.request_id);
|
||||
});
|
||||
|
||||
test('lost purchase survives webview reopen and replays same id/body without a second charge',async()=>{
|
||||
const h=harness(),receipts=new Map();let charges=0;
|
||||
const backend=async(path,body)=>{const fingerprint=JSON.stringify(body);if(receipts.has(body.request_id)){assert.equal(receipts.get(body.request_id).fingerprint,fingerprint);return {...receipts.get(body.request_id).receipt,replayed:true};}charges++;const receipt={ok:true,action:'purchase',offer_id:body.offer_id,charged_cents:250};receipts.set(body.request_id,{fingerprint,receipt});throw new Error('response lost after charge');};
|
||||
h.c.post=backend;await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/response lost/);
|
||||
const saved=JSON.parse(h.store.get('contest-pending:commerce:123'));
|
||||
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"model-day"})'),/Сначала проверь/);
|
||||
const reopened=harness(h.store);reopened.c.post=backend;reopened.c.current='econ';
|
||||
await reopened.run('contestPerform("commerce",{},true)');assert.equal(charges,1);assert.equal(reopened.store.size,0);
|
||||
assert.match(reopened.run('contestState.notices.commerce'),/сохранённая квитанция/);assert.equal(receipts.has(saved.body.request_id),true);
|
||||
});
|
||||
|
||||
test('lost private submission/review retains raw body and cannot silently become a new mutation',async()=>{
|
||||
for(const action of [{action:'submit',kind:'bug',category:'high',title:'Private report',description:'Detailed safe reproduction of the defect.',proof:'safe-request-id'},{action:'review',id:8,decision:'accepted',reward_rep:5,reason:'Independently reproduced'}]){
|
||||
const h=harness();h.c.post=async()=>{throw new Error('network uncertainty');};h.c.body=action;
|
||||
await assert.rejects(h.run('contestMutation("activities",body)'));
|
||||
const saved=JSON.parse(h.store.get('contest-pending:activities:123'));assert.deepEqual({...saved.body,request_id:undefined},{...action,request_id:undefined});
|
||||
const reopened=harness(h.store);await reopened.run('contestMutation("activities",{},true)');assert.deepEqual(reopened.posts[0].body,saved.body);assert.equal(reopened.store.size,0);
|
||||
}
|
||||
});
|
||||
|
||||
test('401, server errors, conflicts and malformed 2xx preserve the uncertain id',async()=>{
|
||||
for(const failure of [Object.assign(new Error('auth'),{status:401,data:{operation_rejected:true}}),Object.assign(new Error('server'),{status:503}),Object.assign(new Error('conflict'),{status:409,data:{error:'request_conflict',operation_rejected:true}}),null]){
|
||||
const h=harness();h.c.post=async()=>{if(failure)throw failure;return {ok:true};};
|
||||
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'));
|
||||
assert.equal(h.store.size,1);assert.equal(h.run('contestState.busy.size'),0);
|
||||
}
|
||||
});
|
||||
|
||||
test('definitive rejection permits correction but storage denial blocks sending',async()=>{
|
||||
const h=harness();h.c.post=async()=>{throw Object.assign(new Error('bad input'),{status:400,data:{operation_rejected:true,error:'invalid_title'}});};
|
||||
await assert.rejects(h.run('contestMutation("activities",{action:"submit",kind:"bug"})'));assert.equal(h.store.size,0);
|
||||
const blocked=harness();blocked.c.localStorage.setItem=()=>{throw new Error('denied');};
|
||||
await assert.rejects(blocked.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Хранилище/);assert.equal(blocked.posts.length,0);
|
||||
});
|
||||
|
||||
test('pending state and late results remain scoped to signed identity',async()=>{
|
||||
const h=harness();h.state('commerce',commerce());h.state('activities',board());
|
||||
h.c.post=async()=>{h.c.resolvedUid='456';return {ok:true,action:'purchase',offer_id:'requests',charged_cents:250};};
|
||||
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Аккаунт изменился/);
|
||||
assert.equal(h.run('contestPending("commerce")'),null);assert.ok(h.store.has('contest-pending:commerce:123'));
|
||||
assert.equal(h.run('commerceOpen("purchase","requests")'),false);assert.equal(h.run('boardOpen("bug")'),false);
|
||||
const view=h.state('activities',board());assert.doesNotMatch(view,/data-board-kind=/);
|
||||
});
|
||||
|
||||
test('in-flight guard prevents double clicks and corrupt pending state fails closed',async()=>{
|
||||
const h=harness();let release;h.c.post=async()=>new Promise(resolve=>{release=resolve;});
|
||||
const first=h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})');
|
||||
await assert.rejects(h.run('contestMutation("commerce",{action:"purchase",offer_id:"requests"})'),/Дождись/);
|
||||
release({ok:true,action:'purchase',offer_id:'requests',charged_cents:250});await first;
|
||||
h.store.set('contest-pending:commerce:123','not-json');assert.match(h.state('commerce',commerce()),/Новые действия заблокированы/);
|
||||
assert.equal(h.run('commerceOpen("purchase","requests")'),false);
|
||||
});
|
||||
|
||||
test('real bound submit handler validates and sends private reports without a public action',async()=>{
|
||||
const h=harness();h.state('activities',board());h.run('boardOpen("bug")');
|
||||
const form=h.get('#contest-form');form.fields=validBug().fields;
|
||||
await form.listeners.get('submit')[0]({target:form,preventDefault(){}});
|
||||
assert.equal(h.posts.length,1);assert.equal(h.posts[0].path,'activities/action');assert.equal(h.posts[0].body.kind,'bug');
|
||||
assert.equal(h.get('#contestdlg').open,false);assert.equal(h.store.size,0);
|
||||
});
|
||||
|
||||
test('real bound invoice confirmation creates a payable invoice, never a wallet credit',async()=>{
|
||||
const h=harness();h.c.current='econ';h.state('commerce',commerce());
|
||||
assert.equal(h.run('commerceOpen("create_invoice","topup")'),true);
|
||||
const form=h.get('#contest-form');
|
||||
await form.listeners.get('submit')[0]({target:form,preventDefault(){}});
|
||||
assert.equal(h.posts[0].path,'commerce/action');assert.equal(h.posts[0].body.action,'create_invoice');assert.equal(h.posts[0].body.offer_id,'topup');
|
||||
assert.match(h.run('contestState.notices.commerce'),/Деньги ещё не зачислены/);assert.equal(h.store.size,0);
|
||||
});
|
||||
|
||||
test('creating/uncertain invoice or inconsistent paid receipt is not a false success',async()=>{
|
||||
for(const result of [
|
||||
{ok:true,action:'create_invoice',invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'uncertain',pay_url:'https://example.org/pay'}},
|
||||
{ok:true,action:'check_invoice',paid:true,credited_cents:500,invoice:{id:'invoice-one',currency:'USD',amount_cents:500,status:'pending'}}
|
||||
]){
|
||||
const h=harness();h.c.post=async()=>result;h.c.body=result.action==='create_invoice'?{action:result.action,offer_id:'topup'}:{action:result.action,invoice_id:'invoice-one'};
|
||||
await assert.rejects(h.run('contestMutation("commerce",body)'),/квитанцию/);assert.equal(h.store.size,1);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Daily HTTP boundary contracts: server-authoritative values and honest state."""
|
||||
import json
|
||||
import sqlite3
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from test_http_contract import namespace
|
||||
|
||||
|
||||
class Request(dict):
|
||||
def __init__(self, body=None, fail=False):
|
||||
super().__init__(uid=42)
|
||||
self.body = {} if body is None else body
|
||||
self.fail = fail
|
||||
|
||||
async def json(self):
|
||||
if self.fail:
|
||||
raise ValueError('invalid JSON')
|
||||
return self.body
|
||||
|
||||
|
||||
def daily_namespace(payload, calls):
|
||||
def status(*args, **kwargs):
|
||||
calls.append(('status', args, kwargs))
|
||||
return dict(payload)
|
||||
def claim(*args, **kwargs):
|
||||
calls.append(('claim', args, kwargs))
|
||||
return dict(payload)
|
||||
return namespace(['_db_busy', '_json_body', '_daily_status_sync', '_daily_claim_sync',
|
||||
'_daily_http_status', 'api_bonus', 'api_daily'],
|
||||
daily_checkin=SimpleNamespace(status=status, claim=claim),
|
||||
quest_economy=SimpleNamespace(earned_rank=lambda *args: 2),
|
||||
BADGES={}, RANK_REFS={}, REF_NEW_ID_MIN=9_000_000_000)
|
||||
|
||||
|
||||
class DailyHTTPTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_get_only_reads_status_and_preserves_pending(self):
|
||||
payload = {'ok': True, 'claimed': True, 'paid': False, 'pending': True, 'face': 3}
|
||||
calls = []
|
||||
env = daily_namespace(payload, calls)
|
||||
response = await env['api_bonus'](Request())
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(json.loads(response.body), payload)
|
||||
self.assertEqual([call[0] for call in calls], ['status'])
|
||||
self.assertEqual(calls[0][1][2], 42)
|
||||
self.assertEqual(response.headers.get('Cache-Control'), 'no-store')
|
||||
|
||||
async def test_post_ignores_client_uid_face_rank_and_amount(self):
|
||||
payload = {'ok': True, 'claimed': True, 'paid': True, 'pending': False,
|
||||
'face': 2, 'units': 12_000_000, 'usd': 24}
|
||||
calls = []
|
||||
env = daily_namespace(payload, calls)
|
||||
response = await env['api_daily'](Request({'uid': 999, 'face': 6, 'value': 6,
|
||||
'rank': 999, 'units': 999999999}))
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(json.loads(response.body), payload)
|
||||
self.assertEqual(calls, [('claim', ('/temporary/bot.db', '/temporary/gateway.db', 42, 2),
|
||||
{'source': 'miniapp'})])
|
||||
|
||||
async def test_repeated_paid_claim_is_200_with_original_result(self):
|
||||
payload = {'ok': True, 'claimed': True, 'paid': True, 'already': True,
|
||||
'pending': False, 'face': 1, 'units': 5_000_000, 'usd': 10}
|
||||
calls = []
|
||||
env = daily_namespace(payload, calls)
|
||||
response = await env['api_daily'](Request())
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(json.loads(response.body), payload)
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
async def test_pending_failed_credit_is_503_not_paid(self):
|
||||
payload = {'ok': False, 'error': 'error', 'claimed': True, 'paid': False,
|
||||
'pending': True, 'face': 4}
|
||||
calls = []
|
||||
env = daily_namespace(payload, calls)
|
||||
response = await env['api_daily'](Request())
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertFalse(json.loads(response.body)['paid'])
|
||||
|
||||
async def test_blocked_and_no_wallet_have_distinct_failure_statuses(self):
|
||||
for error, expected in [('blocked', 403), ('user', 403), ('wallet', 409)]:
|
||||
calls = []
|
||||
env = daily_namespace({'ok': False, 'error': error}, calls)
|
||||
response = await env['api_daily'](Request())
|
||||
self.assertEqual(response.status, expected, error)
|
||||
|
||||
async def test_malformed_json_is_rejected_before_claim(self):
|
||||
calls = []
|
||||
env = daily_namespace({'ok': True}, calls)
|
||||
with self.assertRaises(Exception) as caught:
|
||||
await env['api_daily'](Request(fail=True))
|
||||
self.assertEqual(getattr(caught.exception, 'status', None), 400)
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
async def test_sqlite_failure_is_503_for_both_boundaries(self):
|
||||
def busy(_uid):
|
||||
raise sqlite3.OperationalError('database is locked')
|
||||
for handler, worker in [('api_bonus', '_daily_status_sync'),
|
||||
('api_daily', '_daily_claim_sync')]:
|
||||
calls = []
|
||||
env = daily_namespace({'ok': True}, calls)
|
||||
env[worker] = busy
|
||||
with self.assertLogs('http-contract', level='ERROR'):
|
||||
response = await env[handler](Request())
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertEqual(json.loads(response.body)['error'], 'db_busy')
|
||||
self.assertEqual(calls, [])
|
||||
|
||||
async def test_retired_games_stay_retired(self):
|
||||
import ast
|
||||
from test_http_contract import ROOT
|
||||
tree = ast.parse((ROOT / 'bot' / 'webapp' / 'server.py').read_text(encoding='utf-8'))
|
||||
routes = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
||||
if node.func.attr.startswith('add_') and len(node.args) >= 2:
|
||||
path, handler = node.args[:2]
|
||||
if isinstance(path, ast.Constant) and isinstance(handler, ast.Name):
|
||||
routes[(node.func.attr, path.value)] = handler.id
|
||||
self.assertEqual(routes[('add_get', '/api/bonus')], 'api_bonus')
|
||||
self.assertEqual(routes[('add_post', '/api/daily')], 'api_daily')
|
||||
self.assertEqual(routes[('add_post', '/api/spin')], 'api_retired_bonus')
|
||||
self.assertEqual(routes[('add_post', '/api/task')], 'api_retired_bonus')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Focused regression tests for the daily cube wallet gate.
|
||||
|
||||
Synthetic temp SQLite only. The only source-level assertion is that
|
||||
``_daily_flow`` no longer accepts a caller-supplied token flag.
|
||||
"""
|
||||
import ast
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import daily_checkin
|
||||
import quest_economy
|
||||
|
||||
UID = 1001
|
||||
HERE = Path(__file__).resolve().parent
|
||||
BOT = HERE.parent / "bot" / "grok_bot.py"
|
||||
|
||||
|
||||
def _bot_db(path, token_name=None):
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
con = sqlite3.connect(str(path))
|
||||
con.executescript("""
|
||||
CREATE TABLE users(
|
||||
tg_id INTEGER PRIMARY KEY, token_name TEXT, banned INTEGER DEFAULT 0,
|
||||
api_blocked INTEGER DEFAULT 0, quiz_last TEXT, last_checkin TEXT,
|
||||
gate_member_ok INTEGER, gate_member_ts INTEGER DEFAULT 0,
|
||||
created INTEGER DEFAULT 0, lang TEXT, badge_lock INTEGER DEFAULT 0,
|
||||
badge_until INTEGER DEFAULT 0, points INTEGER DEFAULT 0, rep INTEGER DEFAULT 0);
|
||||
CREATE TABLE econ_tx(
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, src INTEGER NOT NULL, dst INTEGER NOT NULL,
|
||||
units INTEGER NOT NULL, type TEXT NOT NULL, ts INTEGER NOT NULL, ref TEXT,
|
||||
wallet_id INTEGER);
|
||||
CREATE TABLE kv(k TEXT PRIMARY KEY, v TEXT);
|
||||
CREATE TABLE group_log(uid INTEGER, ts INTEGER);
|
||||
""")
|
||||
con.execute("INSERT INTO users(tg_id,token_name,lang) VALUES(?,?,'ru')", (UID, token_name))
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def _gw_db(path, token_name, token_id=7, remain=0, status=1, deleted_at=None):
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
con = sqlite3.connect(str(path))
|
||||
con.executescript("""
|
||||
CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT,
|
||||
banned INTEGER DEFAULT 0, api_blocked INTEGER DEFAULT 0);
|
||||
CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, remain_quota INTEGER,
|
||||
status INTEGER DEFAULT 1, deleted_at INTEGER);
|
||||
""")
|
||||
con.execute("INSERT INTO users(tg_id,token_name) VALUES(?,?)", (UID, token_name))
|
||||
con.execute("INSERT INTO tokens(id,name,remain_quota,status,deleted_at) VALUES(?,?,?,?,?)",
|
||||
(token_id, token_name, remain, status, deleted_at))
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def _env(tmp_path, token_name, bot_token_name=None):
|
||||
bot = tmp_path / "bot.db"
|
||||
gw = tmp_path / "gw.db"
|
||||
_bot_db(bot, bot_token_name)
|
||||
_gw_db(gw, token_name)
|
||||
quest_economy.prepare(str(bot), str(gw))
|
||||
return str(bot), str(gw)
|
||||
|
||||
|
||||
def _count(path, sql, args=()):
|
||||
con = sqlite3.connect(path)
|
||||
try:
|
||||
return con.execute(sql, args).fetchone()[0]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def test_canonical_live_key_rolls_even_when_binding_is_empty(tmp_path):
|
||||
bot, gw = _env(tmp_path, "tg1001", bot_token_name=None)
|
||||
st = daily_checkin.claim(bot, gw, UID, 1, now=int(time.time()), value=3, source="bot")
|
||||
assert st.get("ok") is True, st
|
||||
assert st.get("error") is None
|
||||
assert _count(bot, "SELECT COUNT(*) FROM econ_tx WHERE ref=?", ("daily:%d:%s" % (UID, daily_checkin._day()),)) == 1
|
||||
|
||||
|
||||
def test_only_unbound_secondary_key_is_refused_without_consuming_day(tmp_path):
|
||||
bot, gw = _env(tmp_path, "tg1001-k2", bot_token_name=None)
|
||||
now = int(time.time())
|
||||
st = daily_checkin.claim(bot, gw, UID, 1, now=now, value=3, source="bot")
|
||||
assert st.get("ok") is False
|
||||
assert st.get("error") == "wallet"
|
||||
assert st.get("paid") is not True
|
||||
day = daily_checkin._day(now)
|
||||
assert _count(bot, "SELECT COUNT(*) FROM econ_tx WHERE ref=?", ("daily:%d:%s" % (UID, day),)) == 0
|
||||
assert _count(bot, "SELECT COUNT(*) FROM kv WHERE k LIKE 'ec_ddice:%' OR k LIKE 'ec_dice:%' "
|
||||
"OR k LIKE 'ec_q:%'") == 0
|
||||
assert _count(bot, "SELECT COUNT(*) FROM users WHERE tg_id=? AND last_checkin IS NULL", (UID,)) == 1
|
||||
|
||||
|
||||
def test_bound_secondary_has_a_wallet(tmp_path):
|
||||
# Existing explicit binding is wallet authority even for a secondary name.
|
||||
bot, gw = _env(tmp_path, "tg1001-k2", bot_token_name="tg1001-k2")
|
||||
st = daily_checkin.status(bot, gw, UID, rank=1, now=int(time.time()))
|
||||
assert st.get("ok") is True, st
|
||||
assert st.get("wallet") is True
|
||||
assert st.get("claimed") is False
|
||||
|
||||
|
||||
def test_pm_binding_has_a_wallet(tmp_path):
|
||||
bot, gw = _env(tmp_path, "pm1001", bot_token_name="pm1001")
|
||||
st = daily_checkin.status(bot, gw, UID, rank=1, now=int(time.time()))
|
||||
assert st.get("ok") is True, st
|
||||
assert st.get("wallet") is True
|
||||
|
||||
|
||||
@pytest.mark.skipif(not BOT.exists(), reason="run beside the patched iishko_bot.py")
|
||||
def test_daily_flow_has_no_caller_token_flag():
|
||||
tree = ast.parse(BOT.read_text(encoding="utf-8"))
|
||||
flow = None
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "_daily_flow":
|
||||
flow = node
|
||||
break
|
||||
assert flow is not None
|
||||
assert [a.arg for a in flow.args.args] == ["bot", "chat_id", "uid"]
|
||||
assert "token_ok" not in {n.id for n in ast.walk(flow) if isinstance(n, ast.Name)}
|
||||
|
||||
calls = [n for n in ast.walk(tree)
|
||||
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
|
||||
and n.func.id == "_daily_flow"]
|
||||
assert len(calls) == 2
|
||||
assert all(len(call.args) == 3 for call in calls)
|
||||
|
||||
src = BOT.read_text(encoding="utf-8")
|
||||
assert 'if not st.get("wallet")' in src
|
||||
assert '{**st, "ok": False, "error": "wallet"}' in src
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"state,expected_calls,error",
|
||||
[
|
||||
({"ok": True, "claimed": False, "wallet": True}, ["roll"], None),
|
||||
({"ok": True, "claimed": False, "wallet": False}, [], "wallet"),
|
||||
({"ok": True, "claimed": True, "pending": True, "wallet": True}, ["claim"], None),
|
||||
({"ok": True, "claimed": True, "paid": True, "wallet": True}, [], None),
|
||||
({"ok": False, "error": "blocked"}, [], "blocked"),
|
||||
],
|
||||
)
|
||||
def test_daily_flow_uses_authoritative_wallet_and_never_rerolls_paid(state, expected_calls, error):
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
tree = ast.parse(BOT.read_text(encoding="utf-8"))
|
||||
flow = next(n for n in tree.body if isinstance(n, ast.AsyncFunctionDef)
|
||||
and n.name == "_daily_flow")
|
||||
calls = []
|
||||
|
||||
async def status(uid, rank):
|
||||
return dict(state)
|
||||
|
||||
async def roll(*args):
|
||||
calls.append("roll")
|
||||
return {"ok": True, "paid": True}
|
||||
|
||||
async def claim(*args):
|
||||
calls.append("claim")
|
||||
return {"ok": True, "paid": True}
|
||||
|
||||
namespace = {
|
||||
"asyncio": asyncio, "log": logging.getLogger(__name__),
|
||||
"_daily_rank": lambda uid: 1, "_daily_status": status,
|
||||
"_daily_roll": roll, "_daily_claim": claim, "_daily_body": lambda st, uid: st,
|
||||
}
|
||||
exec(compile(ast.Module(body=[flow], type_ignores=[]), str(BOT), "exec"), namespace)
|
||||
_, result = asyncio.run(namespace["_daily_flow"](object(), 1, UID))
|
||||
assert calls == expected_calls
|
||||
assert result.get("error") == error
|
||||
@@ -0,0 +1,62 @@
|
||||
import ast
|
||||
import asyncio
|
||||
from contextvars import ContextVar
|
||||
from pathlib import Path
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
|
||||
SOURCE = Path(__file__).parents[1] / "bot" / "grok_bot.py"
|
||||
|
||||
|
||||
def load_middleware(name, getter, effort):
|
||||
tree = ast.parse(SOURCE.read_text(encoding="utf-8"))
|
||||
function = next(node for node in tree.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == name)
|
||||
function.decorator_list = []
|
||||
namespace = {"asyncio": asyncio, "EFFORT_VAR": effort, "_effort_get": getter}
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), str(SOURCE), "exec"), namespace)
|
||||
return namespace[name]
|
||||
|
||||
|
||||
class EffortMiddlewareTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_reads_preferences_off_loop_and_sets_context_for_handler(self):
|
||||
main_thread = threading.get_ident()
|
||||
for name in ("_effort_mw", "_effort_cb_mw"):
|
||||
with self.subTest(middleware=name):
|
||||
effort = ContextVar("effort_under_test", default="unset")
|
||||
worker_threads = []
|
||||
|
||||
def getter(uid):
|
||||
worker_threads.append(threading.get_ident())
|
||||
self.assertEqual(uid, 123)
|
||||
return "max"
|
||||
|
||||
async def handler(event, data):
|
||||
self.assertEqual(effort.get(), "max")
|
||||
return "handled"
|
||||
|
||||
middleware = load_middleware(name, getter, effort)
|
||||
event = SimpleNamespace(from_user=SimpleNamespace(id=123))
|
||||
self.assertEqual(await middleware(handler, event, {}), "handled")
|
||||
self.assertEqual(len(worker_threads), 1)
|
||||
self.assertNotEqual(worker_threads[0], main_thread,
|
||||
"SQLite preference read must not block the event loop")
|
||||
|
||||
async def test_no_user_does_not_read_database(self):
|
||||
for name in ("_effort_mw", "_effort_cb_mw"):
|
||||
with self.subTest(middleware=name):
|
||||
reads = []
|
||||
effort = ContextVar("no_user_effort", default="unset")
|
||||
middleware = load_middleware(name, lambda uid: reads.append(uid), effort)
|
||||
|
||||
async def handler(event, data):
|
||||
return effort.get()
|
||||
|
||||
self.assertEqual(await middleware(handler, SimpleNamespace(from_user=None), {}), "unset")
|
||||
self.assertEqual(reads, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Execute the real proxy AST with isolated auth and upstream boundaries; no network/DB."""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import sys
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
import pytest
|
||||
from yarl import URL
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from request_effort import InvalidEffort, read_effort
|
||||
|
||||
SKINS = [ROOT / "gateway" / "grok-web-skin.py"]
|
||||
if os.environ.get("IISHKO_CANDIDATE_SKIN"):
|
||||
SKINS.append(Path(os.environ["IISHKO_CANDIDATE_SKIN"]))
|
||||
|
||||
|
||||
def exercise(source, endpoint, payload, blocked=False):
|
||||
tree = ast.parse(source.read_text(encoding="utf-8"))
|
||||
names = {"proxy", "_dev_role_incompat_model", "_normalize_developer_roles"}
|
||||
nodes: list[ast.stmt] = [node for node in tree.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
|
||||
assert {node.name for node in nodes if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))} == names
|
||||
sent = []
|
||||
gates = []
|
||||
raw = (" " + json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
|
||||
class Session:
|
||||
closed = False
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
sent.append((method, str(url), kwargs["data"]))
|
||||
return self
|
||||
|
||||
async def __aenter__(self):
|
||||
return SimpleNamespace(status=200)
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def gate(key):
|
||||
gates.append(key)
|
||||
return blocked, "Access denied"
|
||||
|
||||
async def relay(*args, **kwargs):
|
||||
return web.Response(body=b'{"ok":true}', content_type="application/json")
|
||||
|
||||
async def relay_request(req, session, url, *, body, **kwargs):
|
||||
async with session.request(req.method, url, data=body) as upstream:
|
||||
return await relay(req, upstream)
|
||||
|
||||
async def read():
|
||||
return raw
|
||||
|
||||
namespace = {
|
||||
"asyncio": asyncio, "aiohttp": aiohttp, "json": json, "time": time,
|
||||
"web": web, "URL": URL, "LOG": logging.getLogger(__name__),
|
||||
"InvalidEffort": InvalidEffort, "read_effort": read_effort,
|
||||
"normalize_auth_headers": dict, "response_headers": dict,
|
||||
"GateUnavailable": type("GateUnavailable", (Exception,), {}),
|
||||
"gate_check": gate, "_rl_check_sync": lambda *args: None,
|
||||
"_DEV_ROLE_INCOMPAT_PREFIXES": ("qwen", "glm", "deepseek", "kimi"),
|
||||
"SKIP": (), "_GEN_PATHS": ("/v1/chat/completions", "/v1/responses"),
|
||||
"SESSION_KEY": "generation", "CONTROL_SESSION_KEY": "control",
|
||||
"PROVIDER_KEY": "provider", "UPSTREAM": "http://isolated.invalid",
|
||||
"_key_balance_usd": lambda *args: None,
|
||||
"relay_api": relay, "relay_api_request": relay_request,
|
||||
}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])),
|
||||
str(source), "exec"), namespace)
|
||||
req = SimpleNamespace(path=endpoint, raw_path=endpoint, method="POST", cookies={},
|
||||
headers={"Authorization": "Bearer isolated-test"}, read=read,
|
||||
app={"generation": Session()})
|
||||
response = asyncio.run(namespace["proxy"](req))
|
||||
assert gates == ["isolated-test"], "account policy must still run before dispatch"
|
||||
return response, sent, raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/chat/completions", "/v1/responses"])
|
||||
@pytest.mark.parametrize("effort", [{"reasoning_effort": "low"},
|
||||
{"reasoning": {"effort": "high"}},
|
||||
{"reasoning_effort": "high", "reasoning": {"effort": "high"}}])
|
||||
def test_effort_reaches_upstream_without_reserializing(skin, endpoint, effort):
|
||||
payload = {"model": "deepseek-v4-pro", "messages": [{"role": "user", "content": "Привет"}],
|
||||
"tools": [], "stream": True, **effort}
|
||||
response, sent, raw = exercise(skin, endpoint, payload)
|
||||
assert response.status == 200 and response.body == b'{"ok":true}'
|
||||
assert len(sent) == 1
|
||||
assert sent[0][2] == raw
|
||||
assert json.loads(sent[0][2]) == payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/chat/completions", "/v1/responses"])
|
||||
@pytest.mark.parametrize("effort", [{"effort": "high"}, {"reasoning_effort": 1},
|
||||
{"reasoning_effort": " "},
|
||||
{"reasoning_effort": "low", "reasoning": {"effort": "high"}}])
|
||||
def test_invalid_effort_never_dispatches(skin, endpoint, effort):
|
||||
response, sent, _ = exercise(skin, endpoint, {"model": "deepseek-v4-pro", **effort})
|
||||
assert response.status == 400
|
||||
assert json.loads(response.body)["error"]["code"] == "invalid_effort"
|
||||
assert not sent
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
def test_effort_does_not_bypass_account_policy(skin):
|
||||
response, sent, _ = exercise(skin, "/v1/chat/completions",
|
||||
{"model": "deepseek-v4-pro", "reasoning_effort": "high"}, blocked=True)
|
||||
assert response.status == 403
|
||||
assert json.loads(response.body)["error"]["code"] == "access_blocked"
|
||||
assert not sent
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Isolated cents/payment/entitlement contracts; never contact payment services."""
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import closing
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'bot'))
|
||||
import gateway_commerce as commerce
|
||||
|
||||
OFFERS = [
|
||||
{'id': 'wallet-test', 'kind': 'wallet_topup', 'price_cents': 1000, 'title': 'Offline top-up'},
|
||||
{'id': 'requests-test', 'kind': 'extra_requests', 'price_cents': 600, 'requests': 500},
|
||||
{'id': 'model-test', 'kind': 'model_pass', 'price_cents': 700, 'model': 'offline-premium'},
|
||||
]
|
||||
NOW = 1792922400
|
||||
|
||||
|
||||
class CommerceTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.db = str(Path(temp.name) / 'bot.db')
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE users(tg_id INTEGER PRIMARY KEY,banned INTEGER DEFAULT 0,
|
||||
api_blocked INTEGER DEFAULT 0,rank_cache INTEGER DEFAULT 1,rep INTEGER DEFAULT 0,
|
||||
badge_lock INTEGER DEFAULT 0,badge_until INTEGER DEFAULT 0);
|
||||
INSERT INTO users(tg_id) VALUES(123),(456);
|
||||
CREATE TABLE community_wallets(uid INTEGER PRIMARY KEY,balance INTEGER NOT NULL);
|
||||
INSERT INTO community_wallets VALUES(123,900000);
|
||||
''')
|
||||
commerce.init_db(self.db)
|
||||
self.calls = []
|
||||
self.remote = None
|
||||
self.counter = 300
|
||||
|
||||
async def provider(token, method, data):
|
||||
self.assertEqual(token, 'offline-token')
|
||||
# A provider call must never retain a SQLite write transaction.
|
||||
if not getattr(self, 'concurrent_checks', False):
|
||||
with closing(sqlite3.connect(self.db, timeout=0.1)) as con:
|
||||
con.execute('BEGIN IMMEDIATE')
|
||||
con.rollback()
|
||||
self.calls.append((method, data.copy()))
|
||||
if method == 'createInvoice':
|
||||
self.counter += 1
|
||||
self.remote = dict(data, invoice_id=self.counter, status='active',
|
||||
bot_invoice_url='https://t.me/CryptoBot?start=offline')
|
||||
return self.remote.copy()
|
||||
self.assertEqual(method, 'getInvoices')
|
||||
self.assertEqual(data, {'invoice_ids': str(self.counter)})
|
||||
return {'items': [self.remote.copy()]}
|
||||
|
||||
self.provider = AsyncMock(side_effect=provider)
|
||||
patcher = patch.object(commerce, '_cp_post', self.provider)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def sql(self, sql, args=()):
|
||||
with closing(sqlite3.connect(self.db)) as con:
|
||||
result = con.execute(sql, args).fetchall()
|
||||
con.commit()
|
||||
return result
|
||||
|
||||
async def act(self, action, request_id, uid=123, offers=OFFERS, token='offline-token', **params):
|
||||
return await commerce.act(self.db, uid, dict(action=action, request_id=request_id, **params),
|
||||
offers, token, NOW)
|
||||
|
||||
async def invoice(self, request_id='offline-create-invoice'):
|
||||
result = await self.act('create_invoice', request_id, offer_id='wallet-test')
|
||||
return result['invoice']['id']
|
||||
|
||||
async def credit(self):
|
||||
identity = await self.invoice()
|
||||
self.remote['status'] = 'paid'
|
||||
return await self.act('check_invoice', 'offline-check-invoice', invoice_id=identity)
|
||||
|
||||
def test_schema_restart_never_creates_a_balance_or_converts_community_coins(self):
|
||||
commerce.init_db(self.db)
|
||||
state = commerce.snapshot(self.db, 123, OFFERS, 'offline-token', NOW)
|
||||
self.assertEqual(state['wallet_cents'], 0)
|
||||
self.assertEqual(state['currency'], 'USD')
|
||||
self.assertEqual(state['history'], [])
|
||||
self.assertEqual(self.sql('SELECT balance FROM community_wallets'), [(900000,)])
|
||||
self.assertEqual(self.sql('SELECT * FROM commerce_wallets'), [])
|
||||
|
||||
async def test_missing_config_and_token_are_explicit_without_fake_invoices(self):
|
||||
state = commerce.snapshot(self.db, 123)
|
||||
self.assertFalse(state['payment_enabled'])
|
||||
self.assertEqual(state['offers'], [])
|
||||
self.assertEqual(state['unavailable_reason'], 'commerce_unavailable')
|
||||
for action, offers, token, expected in (
|
||||
('purchase', [], 'offline-token', 'commerce_unavailable'),
|
||||
('create_invoice', [], 'offline-token', 'commerce_unavailable'),
|
||||
('create_invoice', OFFERS, '', 'payment_unavailable'),
|
||||
):
|
||||
with self.subTest(action=action, token=bool(token)):
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act(action, 'unavailable-test-id', offers=offers, token=token,
|
||||
offer_id='wallet-test' if action == 'create_invoice' else 'requests-test')
|
||||
self.assertEqual(caught.exception.status, 503)
|
||||
self.assertEqual(caught.exception.code, expected)
|
||||
self.provider.assert_not_awaited()
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_invoices'), [(0,)])
|
||||
|
||||
async def test_create_replay_uses_one_remote_invoice_and_saves_expected_fields(self):
|
||||
first = await self.act('create_invoice', 'invoice-create-replay', offer_id='wallet-test')
|
||||
again = await self.act('create_invoice', 'invoice-create-replay', offer_id='wallet-test')
|
||||
self.assertEqual(first['invoice'], again['invoice'])
|
||||
self.assertTrue(again['replayed'])
|
||||
self.assertEqual(self.provider.await_count, 1)
|
||||
self.assertEqual(self.sql('SELECT uid,amount_cents,currency,provider_invoice_id,status FROM commerce_invoices'),
|
||||
[(123, 1000, 'USD', 301, 'pending')])
|
||||
self.assertEqual(self.calls[0][1]['amount'], '10.00')
|
||||
self.assertEqual(self.calls[0][1]['fiat'], 'USD')
|
||||
self.assertNotIn('payload', json.dumps(first))
|
||||
self.assertEqual(first['state']['wallet_cents'], 0)
|
||||
|
||||
async def test_verified_payment_settles_exactly_once_with_same_and_new_request_ids(self):
|
||||
identity = await self.invoice()
|
||||
self.remote['status'] = 'paid'
|
||||
first = await self.act('check_invoice', 'settle-replay-one', invoice_id=identity)
|
||||
replay = await self.act('check_invoice', 'settle-replay-one', invoice_id=identity)
|
||||
other = await self.act('check_invoice', 'settle-replay-two', invoice_id=identity)
|
||||
self.assertTrue(first['paid'])
|
||||
self.assertTrue(replay['replayed'])
|
||||
self.assertTrue(other['paid'])
|
||||
self.assertEqual(other['state']['wallet_cents'], 1000)
|
||||
self.assertEqual(self.sql('SELECT delta_cents,kind FROM commerce_ledger'), [(1000, 'payment')])
|
||||
self.assertEqual(self.provider.await_count, 3) # one create, two distinct server checks
|
||||
self.assertEqual(self.sql('SELECT balance FROM community_wallets'), [(900000,)])
|
||||
|
||||
async def test_paid_amount_currency_id_and_payload_must_match_server_expectations(self):
|
||||
identity = await self.invoice()
|
||||
self.remote['status'] = 'paid'
|
||||
original = self.remote.copy()
|
||||
for index, fields in enumerate(({'amount': '10.01'}, {'amount': 'NaN'}, {'amount': 'Infinity'},
|
||||
{'fiat': 'EUR'}, {'currency_type': 'crypto', 'asset': 'USD'},
|
||||
{'invoice_id': 999}, {'payload': 'another-user-binding'})):
|
||||
with self.subTest(fields=fields):
|
||||
self.remote = dict(original, **fields)
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act('check_invoice', 'mismatched-payment-%d' % index, invoice_id=identity)
|
||||
self.assertEqual(caught.exception.code, 'payment_mismatch')
|
||||
self.assertEqual(self.sql('SELECT * FROM commerce_wallets'), [])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_ledger'), [(0,)])
|
||||
self.remote = original
|
||||
result = await self.act('check_invoice', 'matched-payment-final', invoice_id=identity)
|
||||
self.assertEqual(result['state']['wallet_cents'], 1000)
|
||||
|
||||
async def test_other_user_cannot_check_invoice_and_body_cannot_control_uid_amount_or_paid(self):
|
||||
identity = await self.invoice()
|
||||
self.remote['status'] = 'paid'
|
||||
count = self.provider.await_count
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act('check_invoice', 'foreign-invoice-check', uid=456, invoice_id=identity)
|
||||
self.assertEqual(caught.exception.code, 'invoice_not_found')
|
||||
self.assertEqual(self.provider.await_count, count)
|
||||
for field, value in (('uid', 456), ('amount', 1000000), ('paid', True)):
|
||||
body = dict(action='check_invoice', request_id='forged-payment-body', invoice_id=identity)
|
||||
body[field] = value
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await commerce.act(self.db, 123, body, OFFERS, 'offline-token', NOW)
|
||||
self.assertEqual(caught.exception.code, 'invalid_body')
|
||||
self.assertEqual(self.sql('SELECT * FROM commerce_wallets'), [])
|
||||
|
||||
async def test_pending_checks_are_receipted_poll_again_with_a_new_request_id(self):
|
||||
identity = await self.invoice()
|
||||
first = await self.act('check_invoice', 'pending-check-first', invoice_id=identity)
|
||||
self.assertFalse(first['paid'])
|
||||
self.remote['status'] = 'paid'
|
||||
replay = await self.act('check_invoice', 'pending-check-first', invoice_id=identity)
|
||||
self.assertFalse(replay['paid'])
|
||||
final = await self.act('check_invoice', 'pending-check-second', invoice_id=identity)
|
||||
self.assertTrue(final['paid'])
|
||||
self.assertEqual(final['state']['wallet_cents'], 1000)
|
||||
|
||||
async def test_concurrent_payment_checks_can_credit_only_once(self):
|
||||
identity = await self.invoice()
|
||||
self.remote['status'] = 'paid'
|
||||
self.concurrent_checks = True # Another check may legitimately be settling on its own thread.
|
||||
output = await asyncio.gather(*(self.act('check_invoice', 'parallel-payment-%d' % n,
|
||||
invoice_id=identity) for n in range(6)))
|
||||
self.assertTrue(all(item['paid'] for item in output))
|
||||
self.assertEqual(self.sql('SELECT balance_cents FROM commerce_wallets'), [(1000,)])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_ledger'), [(1,)])
|
||||
|
||||
async def test_ambiguous_creation_never_automatically_creates_another_remote_invoice(self):
|
||||
self.provider.side_effect = commerce.CommerceError(503, 'payment_provider_unavailable', 'offline failure')
|
||||
for _ in range(2):
|
||||
with self.assertRaises(commerce.CommerceError):
|
||||
await self.act('create_invoice', 'uncertain-invoice-id', offer_id='wallet-test')
|
||||
self.assertEqual(self.provider.await_count, 1)
|
||||
self.assertEqual(self.sql('SELECT status FROM commerce_invoices'), [('uncertain',)])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_wallets'), [(0,)])
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act('purchase', 'uncertain-invoice-id', offer_id='requests-test')
|
||||
self.assertEqual(caught.exception.code, 'request_conflict')
|
||||
|
||||
async def test_ambiguous_creation_terminalises_after_grace_so_client_mints_new_id(self):
|
||||
# An ambiguous createInvoice failure leaves an inert 'uncertain' row with no
|
||||
# provider_invoice_id and no exposed pay_url.
|
||||
self.provider.side_effect = commerce.CommerceError(503, 'payment_provider_unavailable', 'offline failure')
|
||||
with self.assertRaises(commerce.CommerceError):
|
||||
await self.act('create_invoice', 'grace-terminal-id', offer_id='wallet-test')
|
||||
self.assertEqual(self.sql('SELECT status,provider_invoice_id FROM commerce_invoices'),
|
||||
[('uncertain', None)])
|
||||
body = {'action': 'create_invoice', 'request_id': 'grace-terminal-id', 'offer_id': 'wallet-test'}
|
||||
# Within the grace window a same-request_id retry stays retryable (a concurrent
|
||||
# create could still commit) and never terminalises or creates a second invoice.
|
||||
with self.assertRaises(commerce.CommerceError) as within:
|
||||
await commerce.act(self.db, 123, dict(body), OFFERS, 'offline-token', NOW + 10)
|
||||
self.assertEqual(within.exception.code, 'invoice_unconfirmed')
|
||||
self.assertFalse(within.exception.operation_rejected)
|
||||
# Past the grace window no create can still be in flight, so the retry is
|
||||
# terminal: the client mints a new request_id instead of looping on 503 forever.
|
||||
with self.assertRaises(commerce.CommerceError) as past:
|
||||
await commerce.act(self.db, 123, dict(body), OFFERS, 'offline-token',
|
||||
NOW + commerce.AMBIGUITY_GRACE + 1)
|
||||
self.assertEqual((past.exception.status, past.exception.code), (409, 'invoice_abandoned'))
|
||||
self.assertTrue(past.exception.operation_rejected)
|
||||
self.assertEqual(self.provider.await_count, 1) # never a second createInvoice
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_invoices'), [(1,)])
|
||||
|
||||
async def test_committed_purchase_is_not_masked_by_a_post_commit_snapshot_failure(self):
|
||||
await self.credit() # wallet now holds 1000 cents
|
||||
# The purchase commits, then the best-effort state refresh fails; the committed
|
||||
# receipt must still be returned (state=None) instead of raising a false error
|
||||
# that would make the client believe a charged purchase failed.
|
||||
with patch.object(commerce, 'snapshot',
|
||||
side_effect=commerce.CommerceError(503, 'payment_provider_unavailable', 'refresh down')):
|
||||
result = await self.act('purchase', 'snapshot-mask-id', offer_id='requests-test')
|
||||
self.assertTrue(result['ok'])
|
||||
self.assertEqual((result['action'], result['charged_cents']), ('purchase', 600))
|
||||
self.assertIsNone(result['state'])
|
||||
self.assertEqual(self.sql('SELECT balance_cents FROM commerce_wallets'), [(400,)])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_grants'), [(1,)])
|
||||
|
||||
async def test_simultaneous_spends_cannot_overdraw_or_grant_without_a_debit(self):
|
||||
await self.credit()
|
||||
def spend(index):
|
||||
try:
|
||||
return commerce.purchase(self.db, 123, {
|
||||
'action': 'purchase', 'request_id': 'simultaneous-spend-%d' % index,
|
||||
'offer_id': 'requests-test'}, OFFERS, NOW)
|
||||
except commerce.CommerceError as error:
|
||||
return error.code
|
||||
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||
result = list(pool.map(spend, range(6)))
|
||||
self.assertEqual(sum(isinstance(item, dict) for item in result), 1)
|
||||
self.assertEqual(result.count('insufficient_funds'), 5)
|
||||
self.assertEqual(self.sql('SELECT balance_cents FROM commerce_wallets'), [(400,)])
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_grants'), [(1,)])
|
||||
self.assertEqual(self.sql("SELECT SUM(delta_cents) FROM commerce_ledger"), [(400,)])
|
||||
|
||||
async def test_duplicate_purchase_grants_once_without_rank_or_other_wallet_changes(self):
|
||||
await self.credit()
|
||||
before = self.sql('SELECT * FROM users WHERE tg_id=123')
|
||||
first = await self.act('purchase', 'purchase-request-replay', offer_id='requests-test')
|
||||
replay = await self.act('buy', 'purchase-request-replay', offer_id='requests-test')
|
||||
self.assertTrue(replay['replayed'])
|
||||
self.assertEqual(first['state']['entitlements']['extra_requests'], 500)
|
||||
self.assertEqual(replay['state']['wallet_cents'], 400)
|
||||
self.assertEqual(before, self.sql('SELECT * FROM users WHERE tg_id=123'))
|
||||
self.assertEqual(self.sql('SELECT COUNT(*) FROM commerce_grants'), [(1,)])
|
||||
self.assertEqual(self.sql('SELECT balance FROM community_wallets'), [(900000,)])
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act('purchase', 'purchase-request-replay', offer_id='model-test')
|
||||
self.assertEqual(caught.exception.code, 'request_conflict')
|
||||
|
||||
async def test_extra_requests_expire_at_current_msk_midnight_and_do_not_roll_over(self):
|
||||
await self.credit()
|
||||
before_midnight = NOW - ((NOW + 10800) % 86400) + 86399
|
||||
result = commerce.purchase(self.db, 123, {
|
||||
'action': 'purchase', 'request_id': 'midnight-request-purchase', 'offer_id': 'requests-test'},
|
||||
OFFERS, before_midnight)
|
||||
reset = before_midnight + 1
|
||||
self.assertEqual(result['expires_at'], reset)
|
||||
self.assertEqual(commerce.entitlements(self.db, 123, reset-1)['extra_requests'], 500)
|
||||
self.assertEqual(commerce.entitlements(self.db, 123, reset), commerce._empty_entitlements())
|
||||
self.assertEqual(commerce.entitlements(self.db, 123, reset+86400)['extra_requests'], 0)
|
||||
|
||||
async def test_model_pass_last_24_hours_stale_upstream_scope_is_not_authority(self):
|
||||
await self.credit()
|
||||
result = await self.act('purchase', 'model-pass-purchase', offer_id='model-test')
|
||||
self.assertEqual(result['expires_at'], NOW + 86400)
|
||||
self.assertTrue(commerce.model_access(self.db, 123, 'offline-premium', ['base-model'], NOW))
|
||||
self.assertEqual(commerce.token_model_scope(self.db, 123, ['base-model'], NOW),
|
||||
['base-model', 'offline-premium'])
|
||||
self.assertFalse(commerce.model_access(self.db, 123, 'offline-premium', ['base-model'], NOW+86400))
|
||||
self.assertEqual(commerce.token_model_scope(self.db, 123, ['base-model'], NOW+86400), ['base-model'])
|
||||
self.assertEqual(commerce.managed_model_passes(self.db, 123, NOW+86400), [
|
||||
{'model': 'offline-premium', 'expires_at': NOW+86400, 'active': False, 'base_granted': False}])
|
||||
self.assertTrue(commerce.model_access(self.db, 123, 'offline-premium', ['offline-premium'], NOW+86400))
|
||||
|
||||
async def test_ban_and_subscription_gate_apply_to_receipt_replays_and_model_access(self):
|
||||
await self.credit()
|
||||
await self.act('purchase', 'model-pass-purchase', offer_id='model-test')
|
||||
for flag in ('banned', 'api_blocked'):
|
||||
self.sql('UPDATE users SET '+flag+'=1 WHERE tg_id=123')
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
await self.act('purchase', 'model-pass-purchase', offer_id='model-test')
|
||||
self.assertEqual(caught.exception.code, 'blocked')
|
||||
self.assertEqual(commerce.entitlements(self.db, 123, NOW), commerce._empty_entitlements())
|
||||
self.assertFalse(commerce.model_access(self.db, 123, 'base-model', ['base-model'], NOW))
|
||||
self.sql('UPDATE users SET '+flag+'=0 WHERE tg_id=123')
|
||||
|
||||
def test_bad_operator_configuration_never_becomes_an_implicit_free_offer(self):
|
||||
for offers in ({}, [{'id': 'free', 'kind': 'model_pass', 'price_cents': 0, 'model': 'm'}],
|
||||
[{'id': 'float', 'kind': 'wallet_topup', 'price_cents': 1.25}],
|
||||
[dict(OFFERS[1], requests=True)], [OFFERS[0], OFFERS[0]]):
|
||||
with self.subTest(offers=offers):
|
||||
with self.assertRaises(commerce.CommerceError) as caught:
|
||||
commerce.snapshot(self.db, 123, offers)
|
||||
self.assertEqual(caught.exception.code, 'commerce_config_invalid')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Gateway wiring regressions: model metadata attach point and unpinned effort schema.
|
||||
|
||||
Static/behavioural checks on the canonical skin, plus the live-vintage candidate from
|
||||
skin.baseline.py when ``IISHKO_CANDIDATE_SKIN`` points at it (the Linux stage does not
|
||||
have a Windows path baked in). Boundary claims are proven on the AST of ``proxy()``,
|
||||
not by text offsets: a def or an unrelated symbol earlier in the file must not be able
|
||||
to satisfy them.
|
||||
"""
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
CANON_SKIN = os.path.join(ROOT, "gateway", "grok-web-skin.py")
|
||||
CANDIDATE_SKIN = os.environ.get("IISHKO_CANDIDATE_SKIN")
|
||||
EFFORT_PATHS = ("/v1/chat/completions", "/v1/responses")
|
||||
MODELS_PATHS = ("/v1/models", "/api/user/models")
|
||||
|
||||
SKINS = [CANON_SKIN] + ([CANDIDATE_SKIN] if CANDIDATE_SKIN else [])
|
||||
SKINS = [p for p in SKINS if os.path.exists(p)]
|
||||
SKIN_IDS = ["canonical", "candidate"][:len(SKINS)]
|
||||
|
||||
|
||||
def _read(path):
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return handle.read()
|
||||
|
||||
|
||||
def _parsed(path):
|
||||
source = _read(path)
|
||||
return source, ast.parse(source)
|
||||
|
||||
|
||||
FUNCTION_NODES = (ast.FunctionDef, ast.AsyncFunctionDef)
|
||||
|
||||
|
||||
def _functions(tree):
|
||||
"""Module-level definitions only: a nested def must not shadow the real handler."""
|
||||
return {node.name: node for node in tree.body if isinstance(node, FUNCTION_NODES)}
|
||||
|
||||
|
||||
def _text(node):
|
||||
return ast.dump(node)
|
||||
|
||||
|
||||
def _path_to(node, target):
|
||||
"""Ancestors of ``target`` from ``node`` (outermost first), or None."""
|
||||
if node is target:
|
||||
return [node]
|
||||
for child in ast.iter_child_nodes(node):
|
||||
found = _path_to(child, target)
|
||||
if found is not None:
|
||||
return [node] + found
|
||||
return None
|
||||
|
||||
|
||||
def _function(tree, source, names):
|
||||
functions = _functions(tree)
|
||||
for name in names:
|
||||
if name in functions:
|
||||
return functions[name]
|
||||
pytest.fail("none of %s found in %s" % (names, source))
|
||||
|
||||
|
||||
def _proxy(tree, source):
|
||||
return _function(tree, source, ("proxy", "handle", "handler"))
|
||||
|
||||
|
||||
def _line_of(predicate, root):
|
||||
for node in ast.walk(root):
|
||||
if isinstance(node, ast.stmt) and predicate(node):
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def _contains_call(node, name):
|
||||
return any(isinstance(item, ast.Call)
|
||||
and ((isinstance(item.func, ast.Name) and item.func.id == name)
|
||||
or (isinstance(item.func, ast.Attribute) and item.func.attr == name))
|
||||
for item in ast.walk(node))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS)
|
||||
def test_skin_imports_the_shared_validator(path):
|
||||
source, tree = _parsed(path)
|
||||
assert "from request_effort import InvalidEffort, read_effort" in source
|
||||
imported = {alias.name for node in ast.walk(tree)
|
||||
if isinstance(node, ast.ImportFrom) and node.module == "request_effort"
|
||||
for alias in node.names}
|
||||
assert {"InvalidEffort", "read_effort"} <= imported
|
||||
if os.path.basename(path) != "skin.candidate.py":
|
||||
return
|
||||
# Live vintage ships no pinned relay package; introducing one would not import at all.
|
||||
assert "gateway_providers" not in source
|
||||
for forbidden in ("ProviderError", "denial_response"):
|
||||
assert forbidden not in source, "live vintage has no %s: do not introduce it" % forbidden
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS)
|
||||
def test_effort_guard_precedes_body_rewrites(path):
|
||||
source, tree = _parsed(path)
|
||||
proxy = _proxy(tree, path)
|
||||
parse_stmt = _line_of(
|
||||
lambda node: isinstance(node, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "request_object" for t in node.targets)
|
||||
and isinstance(node.value, ast.Call)
|
||||
and isinstance(node.value.func, ast.Attribute) and node.value.func.attr == "loads", proxy)
|
||||
guard = _line_of(
|
||||
lambda node: isinstance(node, ast.If) and any(isinstance(inner, ast.ExceptHandler)
|
||||
and inner.type is not None
|
||||
and "InvalidEffort" in ast.dump(inner.type)
|
||||
for inner in ast.walk(node)), proxy)
|
||||
normalize = _line_of(
|
||||
lambda node: isinstance(node, ast.If)
|
||||
and _contains_call(node, "_normalize_developer_roles"), proxy)
|
||||
assert parse_stmt is not None and guard is not None and normalize is not None
|
||||
# All three live in proxy() itself, not in module-level helpers sharing a name.
|
||||
assert parse_stmt.lineno < guard.lineno < normalize.lineno
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS)
|
||||
def test_invalid_effort_returns_the_contract_400(path):
|
||||
_source, tree = _parsed(path)
|
||||
proxy = _proxy(tree, path)
|
||||
guard = _line_of(
|
||||
lambda node: isinstance(node, ast.If) and any(isinstance(inner, ast.ExceptHandler)
|
||||
and inner.type is not None
|
||||
and "InvalidEffort" in ast.dump(inner.type)
|
||||
for inner in ast.walk(node)), proxy)
|
||||
assert guard is not None
|
||||
dumped = ast.dump(guard)
|
||||
assert "invalid_effort" in dumped and "invalid_request_error" in dumped
|
||||
assert "retryable" in dumped and "status" in dumped and "400" in dumped
|
||||
# POST-only, gated on the two unpinned endpoints, and the parsed object itself.
|
||||
gated = ast.dump(guard.test) if isinstance(guard, ast.If) else dumped
|
||||
for token in ('"POST"', "/v1/chat/completions", "/v1/responses",
|
||||
"rstrip", "isinstance", "read_effort"):
|
||||
assert token.replace('"', '') in gated.replace('"', ''), token
|
||||
# The guard consumes the parsed dict and only returns an error: it never
|
||||
# re-serializes or rewrites the request bytes.
|
||||
for inner in ast.walk(guard):
|
||||
assert not _contains_call(inner, "json.dumps") or not isinstance(inner, ast.stmt)
|
||||
if isinstance(inner, ast.Return):
|
||||
assert _contains_call(inner, "json_response")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", SKINS, ids=SKIN_IDS)
|
||||
def test_metadata_attach_only_under_models_get_branch(path):
|
||||
_source, tree = _parsed(path)
|
||||
calls = [node for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name) and node.func.id == "_attach_model_metadata"]
|
||||
# Two branches carry the catalogue: the legacy relay() enrichment and the transparent
|
||||
# GET /v1/models hook. Both must stay scoped to a models GET, never to generation.
|
||||
assert len(calls) == 2, "legacy relay branch + transparent /v1/models hook"
|
||||
top_level = {node for node in tree.body if isinstance(node, FUNCTION_NODES)}
|
||||
for call in calls:
|
||||
chain = _path_to(tree, call)
|
||||
owner = [node for node in chain if isinstance(node, FUNCTION_NODES)]
|
||||
assert owner and isinstance(owner[-1], ast.AsyncFunctionDef), "attach must be in a handler"
|
||||
assert owner[-1] in top_level, "attach owner must be a module-level handler"
|
||||
guards = [node for node in chain if isinstance(node, ast.If)]
|
||||
models_guard = [node for node in guards
|
||||
if any(tok in ast.dump(node.test) for tok in MODELS_PATHS)]
|
||||
assert models_guard, "attach must sit under the models branch"
|
||||
get_guard = [node for node in models_guard if "GET" in ast.dump(node.test)]
|
||||
assert get_guard, "models branch must be the GET path"
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SKINS, reason="no skin available")
|
||||
def test_attach_result_is_used_to_reserialize_only_then():
|
||||
path = SKINS[0]
|
||||
_source, tree = _parsed(path)
|
||||
calls = [node for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name) and node.func.id == "_attach_model_metadata"]
|
||||
assert len(calls) == 2, "legacy relay branch + transparent /v1/models hook"
|
||||
for call in calls:
|
||||
owners = [node for node in _path_to(tree, call) if isinstance(node, ast.If)]
|
||||
assert owners, "attach result must gate a re-serialization"
|
||||
reserializing = [node for node in owners
|
||||
if "_attach_model_metadata" in ast.dump(node.test)]
|
||||
assert reserializing, "each attach result must be consumed by its own guard"
|
||||
for node in reserializing:
|
||||
inner = ast.dump(node)
|
||||
assert "dumps" in inner and "encode" in inner
|
||||
|
||||
|
||||
def _load_attach(path):
|
||||
"""Exec only the module-level helper out of the script (no aiohttp side effects)."""
|
||||
_source, tree = _parsed(path)
|
||||
node = next(n for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "_attach_model_metadata")
|
||||
globals_ = {"json": __import__("json"),
|
||||
"model_metadata": __import__("model_metadata")}
|
||||
|
||||
class _Log:
|
||||
def warning(self, *a, **k):
|
||||
pass
|
||||
|
||||
globals_["LOG"] = _Log()
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), path, "exec"), globals_)
|
||||
return globals_["_attach_model_metadata"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SKINS, reason="no skin available")
|
||||
def test_attach_helper_enriches_rows_without_touching_ids():
|
||||
attach = _load_attach(SKINS[0])
|
||||
env = {"object": "list", "data": [{"id": "grok-4.6", "object": "model", "owned_by": "x-ai"},
|
||||
{"id": "unknown-model"}]}
|
||||
assert attach(env) is True
|
||||
assert [row["id"] for row in env["data"]] == ["grok-4.6", "unknown-model"]
|
||||
assert env["data"][0]["owned_by"] == "x-ai"
|
||||
assert env["data"][0]["model_metadata"]["context_window"] == 500000
|
||||
assert env["data"][1]["model_metadata"]["known"] is False
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SKINS, reason="no skin available")
|
||||
def test_attach_helper_keeps_raw_body_when_reference_is_unusable(monkeypatch):
|
||||
attach = _load_attach(SKINS[0])
|
||||
module = sys.modules["model_metadata"]
|
||||
monkeypatch.setattr(module, "attach_rows",
|
||||
lambda rows: (_ for _ in ()).throw(RuntimeError("boom")))
|
||||
env = {"object": "list", "data": [{"id": "grok-4.6"}]}
|
||||
assert attach(env) is False
|
||||
assert env == {"object": "list", "data": [{"id": "grok-4.6"}]}
|
||||
|
||||
|
||||
@pytest.mark.skipif(not SKINS, reason="no skin available")
|
||||
def test_attach_helper_ignores_env_without_model_rows():
|
||||
attach = _load_attach(SKINS[0])
|
||||
env = {"object": "list", "data": [{"object": "model"}]}
|
||||
assert attach(env) is False
|
||||
assert env == {"object": "list", "data": [{"object": "model"}]}
|
||||
@@ -0,0 +1,298 @@
|
||||
"""A provider 403 is not evidence that a user's rank is too low."""
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py'
|
||||
SPEC = importlib.util.spec_from_file_location('audited_gateway_errors', SOURCE)
|
||||
MOD = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(MOD)
|
||||
|
||||
|
||||
class PublicErrorTests(unittest.TestCase):
|
||||
def error(self, status, message, balance=None):
|
||||
return MOD.public_error(status, json.dumps({'error': {'message': message}}).encode(),
|
||||
'/v1/chat/completions', user_balance=balance)
|
||||
|
||||
def test_real_token_model_denial_is_specific_not_a_blanket_rank_claim(self):
|
||||
status, body = self.error(403, 'This token has no access to model gpt-6-luna (request id: audit-123)')
|
||||
self.assertEqual((status, body['error']['code']), (403, 'model_access_denied'))
|
||||
self.assertEqual(body['error']['request_id'], 'audit-123')
|
||||
self.assertIn('старые имена', body['error']['message'])
|
||||
self.assertIn('/profile', body['error']['message'])
|
||||
self.assertNotIn('повысьте ранг', body['error']['message'])
|
||||
|
||||
def test_unknown_provider_forbidden_never_claims_rank_deficiency(self):
|
||||
status, body = self.error(403, 'Access forbidden by provider policy')
|
||||
self.assertEqual((status, body['error']['code']), (403, 'request_forbidden'))
|
||||
self.assertNotIn('повысьте ранг', body['error']['message'])
|
||||
self.assertNotIn('У вашего ключа нет доступа', body['error']['message'])
|
||||
|
||||
def test_provider_billing_still_is_not_a_user_quota_error(self):
|
||||
status, body = self.error(403, 'Free quota exhausted')
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error'))
|
||||
|
||||
def test_bare_upstream_quota_with_user_funds_retains_live_production_fix(self):
|
||||
status, body = self.error(403, 'insufficient_quota', 1000.0)
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error'))
|
||||
|
||||
def test_invalid_key_and_transient_rate_limits_remain_distinct(self):
|
||||
self.assertEqual(self.error(401, 'bad key')[1]['error']['code'], 'invalid_api_key')
|
||||
status, body = self.error(429, 'too many requests')
|
||||
self.assertEqual(status, 429)
|
||||
self.assertTrue(body['error']['retryable'])
|
||||
|
||||
def test_provider_401_never_revokes_the_client_key(self):
|
||||
for message in (
|
||||
'channel error (channel #20247, status code: 401)',
|
||||
'Incorrect API key provided: sk-not-a-user-key'):
|
||||
with self.subTest(message=message):
|
||||
status, body = self.error(401, message)
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_auth_error'))
|
||||
self.assertTrue(body['error']['retryable'])
|
||||
self.assertNotIn('sk-', json.dumps(body))
|
||||
self.assertNotIn('недействителен или отозван', body['error']['message'])
|
||||
|
||||
def test_all_auth_aliases_accept_one_credential_only(self):
|
||||
headers = {'Authorization': 'bearer same', 'X-Api-Key': 'same', 'Api-Key': 'same'}
|
||||
self.assertEqual(MOD.normalize_auth_headers(headers), {'Authorization': 'Bearer same'})
|
||||
self.assertEqual(MOD.normalize_auth_headers({'Api-Key': 'same'}),
|
||||
{'Authorization': 'Bearer same'})
|
||||
with self.assertRaises(ValueError):
|
||||
MOD.normalize_auth_headers({'Authorization': 'Bearer first', 'Api-Key': 'second'})
|
||||
|
||||
def test_fullwidth_precharge_provider_wallet_is_not_the_clients_wallet(self):
|
||||
message = '预扣费额度失败, 用户剩余额度: $0.004652, 需要预扣费额度: $0.168556'
|
||||
status, body = self.error(403, message, 999.32)
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error'))
|
||||
self.assertNotIn('ранг', body['error']['message'])
|
||||
|
||||
def test_real_precharge_shortage_remains_a_client_quota_denial(self):
|
||||
status, body = self.error(403, '预扣费额度失败, 用户剩余额度: $0.01, 需要预扣费额度: $0.50', 0.01)
|
||||
self.assertEqual((status, body['error']['code']), (402, 'insufficient_quota'))
|
||||
self.assertFalse(body['error']['retryable'])
|
||||
|
||||
def test_provider_model_permission_is_not_the_clients_rank(self):
|
||||
status, body = self.error(403, 'Model "claude-sonnet-5-5" not allowed for this key. Allowed: claude')
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_model_denied'))
|
||||
|
||||
def test_upstream_413_does_not_claim_our_40mb_limit_was_hit(self):
|
||||
status, body = MOD.public_error(413, b'not JSON', '/v1/chat/completions', from_upstream=True)
|
||||
self.assertEqual((status, body['error']['code']), (413, 'upstream_request_too_large'))
|
||||
self.assertNotIn('максимальный размер запроса', body['error']['message'])
|
||||
self.assertFalse(body['error']['retryable'])
|
||||
self.assertEqual(MOD.public_error(413, b'', '/v1/chat/completions')[1]['error']['code'],
|
||||
'request_too_large')
|
||||
|
||||
def test_text_only_route_image_rejection_is_honest_and_actionable(self):
|
||||
# glm-5.3 + скриншот: upstream 400 code 1210 «allowed values: ['text']» — не «проверьте имя модели».
|
||||
status, body = self.error(400, "contents.parts.type is invalid, allowed values: ['text'] (code 1210)")
|
||||
self.assertEqual((status, body['error']['code']), (400, 'vision_not_supported'))
|
||||
self.assertFalse(body['error']['retryable'])
|
||||
self.assertIn('не принимает изображения', body['error']['message'])
|
||||
self.assertIn('из истории', body['error']['message'])
|
||||
self.assertIn('другая модель не подставлялась', body['error']['message'])
|
||||
for removed in ('deepseek-v4.1-flash', 'gemini-3.5-flash', 'glm-5.3-prime'):
|
||||
self.assertNotIn(removed, body['error']['message'])
|
||||
|
||||
def test_dead_upstream_route_404_is_retryable_gateway_problem(self):
|
||||
status, body = self.error(404, 'Not Found')
|
||||
self.assertEqual((status, body['error']['code']), (503, 'upstream_route_dead'))
|
||||
self.assertTrue(body['error']['retryable'])
|
||||
|
||||
def test_route_404_mapping_is_scoped_to_relay_paths(self):
|
||||
status, body = MOD.public_error(404, b'Not Found', '/api/show')
|
||||
self.assertEqual((status, body['error']['code']), (404, 'invalid_request'))
|
||||
|
||||
|
||||
class ContentPolicyMessageTests(unittest.TestCase):
|
||||
"""[POLICYMSG 2810] Вердикт модерации апстрима детерминирован: совет «повтори попытку» невыполним."""
|
||||
|
||||
def policy_error(self, code, message, path='/v1/chat/completions'):
|
||||
body = json.dumps({'error': {'code': code, 'message': message}}).encode()
|
||||
return MOD.public_error(400, body, path, from_upstream=True)
|
||||
|
||||
def test_dashscope_inspection_failure_is_non_retryable_policy_code(self):
|
||||
status, body = self.policy_error(
|
||||
'data_inspection_failed', 'DataInspectionFailed: Input data may contain inappropriate content.')
|
||||
err = body['error']
|
||||
self.assertEqual((status, err['code'], err['retryable']), (400, 'content_policy_violation', False))
|
||||
self.assertEqual(err['message'], MOD.CONTENT_POLICY_USERMSG)
|
||||
|
||||
def test_policy_message_states_the_filter_and_a_real_alternative(self):
|
||||
_, body = self.policy_error('content_policy_violation', 'content_policy_violation')
|
||||
msg = body['error']['message']
|
||||
self.assertIn('контент-фильтр', msg)
|
||||
self.assertIn('переформулируй', msg)
|
||||
self.assertIn('другого семейства', msg)
|
||||
self.assertNotIn('не обработала запрос', msg)
|
||||
|
||||
def test_policy_message_does_not_promise_that_a_plain_retry_helps(self):
|
||||
_, body = self.policy_error('content_filter', 'rejected by safety system')
|
||||
msg = body['error']['message']
|
||||
for misleading in ('Повтори попытку', 'повтори попытку', 'Повторите попытку', 'повторите попытку'):
|
||||
self.assertNotIn(misleading, msg)
|
||||
self.assertIn('не поможет', msg)
|
||||
|
||||
def test_openai_content_filter_uses_the_same_honest_text(self):
|
||||
_, body = self.policy_error('content_filter', 'Your request was rejected as a result of our safety system.')
|
||||
self.assertEqual((body['error']['code'], body['error']['message']),
|
||||
('content_policy_violation', MOD.CONTENT_POLICY_USERMSG))
|
||||
|
||||
def test_image_route_policy_rejection_keeps_the_same_contract(self):
|
||||
status, body = self.policy_error('DataInspectionFailed', 'DataInspectionFailed', '/v1/images/generations')
|
||||
self.assertEqual((status, body['error']['code'], body['error']['message']),
|
||||
(400, 'content_policy_violation', MOD.CONTENT_POLICY_USERMSG))
|
||||
|
||||
def test_unsupported_parameter_prose_is_not_a_policy_verdict(self):
|
||||
# [NOPOLICY 2810] структурный код важнее слабой прозы «content_filter» в message.
|
||||
status, body = self.policy_error('unsupported_parameter', 'content_filter unsupported: model-x')
|
||||
self.assertNotEqual(body['error']['code'], 'content_policy_violation')
|
||||
|
||||
def test_strong_provider_marker_wins_over_a_generic_code(self):
|
||||
status, body = self.policy_error(
|
||||
'invalid_request_error', 'DataInspectionFailed: Input data may contain inappropriate content.')
|
||||
self.assertEqual((status, body['error']['code'], body['error']['retryable']),
|
||||
(400, 'content_policy_violation', False))
|
||||
|
||||
def test_weak_marker_without_any_structured_code_still_maps_to_policy(self):
|
||||
raw = json.dumps({'error': {'message': 'request blocked by content_filter'}}).encode()
|
||||
status, body = MOD.public_error(400, raw, '/v1/chat/completions', from_upstream=True)
|
||||
self.assertEqual((status, body['error']['code'], body['error']['message']),
|
||||
(400, 'content_policy_violation', MOD.CONTENT_POLICY_USERMSG))
|
||||
|
||||
def test_bot_imports_the_gateway_text_instead_of_copying_it(self):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
bot_src = (root / 'bot/grok_bot.py').read_text(encoding='utf-8')
|
||||
self.assertIn('from gateway_errors import public_error, CONTENT_POLICY_USERMSG', bot_src)
|
||||
assigned = None
|
||||
for node in ast.walk(ast.parse(bot_src)):
|
||||
if isinstance(node, ast.Assign) and any(getattr(t, 'id', None) == '_POLICY_USERMSG' for t in node.targets):
|
||||
assigned = node.value
|
||||
self.assertIsInstance(assigned, ast.Name, 'бот обязан брать текст из gateway_errors, а не хранить копию')
|
||||
self.assertEqual(assigned.id, 'CONTENT_POLICY_USERMSG')
|
||||
|
||||
def test_no_python_source_ships_the_misleading_retry_advice(self):
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
stale_advice = 'Повтори попытку ' + 'или выбери другую модель' # собрано из частей: тест не содержит искомую строку
|
||||
stale = []
|
||||
for path in root.rglob('*.py'):
|
||||
if 'build' in path.parts or '__pycache__' in path.parts:
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='replace')
|
||||
if stale_advice in text:
|
||||
stale.append(str(path.relative_to(root)))
|
||||
self.assertEqual(stale, [])
|
||||
|
||||
|
||||
class PolicyCodeClassificationTests(unittest.TestCase):
|
||||
"""[POLICYCODE 2810] Политика — точный код/тип вендора (в т.ч. вложенный), а не проза про параметры."""
|
||||
|
||||
def raw_error(self, status, payload, path='/v1/chat/completions'):
|
||||
body = payload if isinstance(payload, (bytes, bytearray)) else json.dumps(payload).encode()
|
||||
return MOD.public_error(status, body, path, from_upstream=True)
|
||||
|
||||
def assert_policy(self, result):
|
||||
status, body = result
|
||||
err = body['error']
|
||||
self.assertEqual((status, err['code'], err['retryable']), (400, 'content_policy_violation', False))
|
||||
self.assertEqual(err['message'], MOD.CONTENT_POLICY_USERMSG)
|
||||
|
||||
def assert_not_policy(self, body):
|
||||
self.assertNotEqual(body['error']['code'], 'content_policy_violation')
|
||||
self.assertNotEqual(body['error']['message'], MOD.CONTENT_POLICY_USERMSG)
|
||||
|
||||
def test_nested_code_only_envelope_is_policy(self):
|
||||
self.assert_policy(self.raw_error(400, {'error': {'error': {'code': 'DataInspectionFailed'}}}))
|
||||
|
||||
def test_type_only_envelope_is_policy(self):
|
||||
self.assert_policy(self.raw_error(
|
||||
400, {'error': {'type': 'content_policy_violation', 'message': 'safety system'}}))
|
||||
|
||||
def test_input_output_inspection_code_variants_are_policy(self):
|
||||
for code in ('InputDataInspectionFailed', 'OutputDataInspectionFailed', 'input_data_inspection_failed'):
|
||||
with self.subTest(code=code):
|
||||
self.assert_policy(self.raw_error(400, {'error': {'code': code}}))
|
||||
|
||||
def test_json_string_message_envelope_is_decoded_to_policy(self):
|
||||
inner = json.dumps({'code': 'OutputDataInspectionFailed',
|
||||
'message': 'Output data may contain inappropriate content.'})
|
||||
self.assert_policy(self.raw_error(400, {'error': {'message': inner}}))
|
||||
|
||||
def test_bare_code_string_payload_is_policy(self):
|
||||
self.assert_policy(self.raw_error(400, b'"data_inspection_failed"'))
|
||||
|
||||
def test_vendor_prefixed_message_without_code_field_is_policy(self):
|
||||
self.assert_policy(self.raw_error(
|
||||
400, {'error': {'message': 'DataInspectionFailed: Input data may contain inappropriate content.'}}))
|
||||
|
||||
def test_classification_is_idempotent_on_normalized_output(self):
|
||||
status, body = self.raw_error(
|
||||
400, {'error': {'code': 'data_inspection_failed',
|
||||
'message': 'Input data may contain inappropriate content.'}})
|
||||
self.assert_policy((status, body))
|
||||
again = MOD.public_error(status, MOD.public_json_dumps(body).encode(), '/v1/chat/completions')
|
||||
self.assertEqual(again, (status, body))
|
||||
|
||||
def test_unsupported_parameter_prose_without_code_is_not_policy(self):
|
||||
_, body = self.raw_error(400, {'error': {'message': 'content_filter unsupported: model-x'}})
|
||||
self.assert_not_policy(body)
|
||||
|
||||
def test_unsupported_content_filter_and_reasoning_effort_mentions_are_not_policy(self):
|
||||
for payload in (
|
||||
{'error': {'code': 'unsupported_parameter',
|
||||
'message': 'content_filter is not supported by this endpoint; '
|
||||
'reasoning_effort also unsupported'}},
|
||||
{'error': {'message': 'unsupported parameters: content_filter, reasoning_effort '
|
||||
'are not valid for this model'}}):
|
||||
with self.subTest(payload=payload['error']['message']):
|
||||
_, body = self.raw_error(400, payload)
|
||||
self.assert_not_policy(body)
|
||||
|
||||
def test_false_marker_in_arbitrary_message_is_not_policy(self):
|
||||
_, body = self.raw_error(400, {'error': {
|
||||
'code': 'model_not_found',
|
||||
'message': 'Model content_filter-v2 does not exist, check content_policy_violation '
|
||||
'docs and data_inspection_failed FAQ'}})
|
||||
self.assert_not_policy(body)
|
||||
|
||||
def test_structured_policy_beats_billing_looking_message(self):
|
||||
self.assert_policy(self.raw_error(403, {'error': {
|
||||
'code': 'data_inspection_failed',
|
||||
'message': 'Free quota exhausted. Please top up your credit balance.'}}))
|
||||
|
||||
def test_text_only_policy_marker_does_not_override_billing_markers(self):
|
||||
_, body = self.raw_error(403, {'error': {
|
||||
'message': 'Free quota exhausted. DataInspectionFailed: retry later'}})
|
||||
self.assertEqual((body['error']['code'], body['error']['retryable']),
|
||||
('upstream_billing_error', True))
|
||||
|
||||
def test_safe_request_id_is_preserved_without_upstream_prose(self):
|
||||
status, body = self.raw_error(400, {'error': {
|
||||
'code': 'DataInspectionFailed',
|
||||
'message': 'Input data may contain inappropriate content.',
|
||||
'request_id': 'req-7f3a-public'}})
|
||||
self.assert_policy((status, body))
|
||||
self.assertEqual(body['error']['request_id'], 'req-7f3a-public')
|
||||
self.assertNotIn('inappropriate', json.dumps(body))
|
||||
|
||||
def test_secret_looking_request_id_is_not_echoed(self):
|
||||
status, body = self.raw_error(
|
||||
400, {'error': {'code': 'content_filter', 'request_id': 'sk-live-secret123'}})
|
||||
self.assert_policy((status, body))
|
||||
self.assertNotIn('request_id', body['error'])
|
||||
self.assertNotIn('sk-live', json.dumps(body))
|
||||
|
||||
def test_deeply_nested_envelope_stays_bounded_and_generic(self):
|
||||
payload = {'code': 'data_inspection_failed'}
|
||||
for _ in range(30):
|
||||
payload = {'error': payload}
|
||||
status, body = self.raw_error(400, payload)
|
||||
self.assertEqual((status, body['error']['code']), (400, 'invalid_request'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,236 @@
|
||||
from contextlib import closing
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for path in (ROOT, ROOT / 'gateway', ROOT / 'src' / 'opt'):
|
||||
sys.path.insert(0, str(path))
|
||||
from gateway_features import AdaptiveLimiter, install
|
||||
|
||||
MSK = timezone(timedelta(hours=3))
|
||||
|
||||
|
||||
class AdmissionTests(unittest.TestCase):
|
||||
def test_heavy_client_yields_light_client_survives_and_limits_recover(self):
|
||||
limiter = AdaptiveLimiter(rpm=40, fair_rpm=2, max_inflight=8, per_key_inflight=8)
|
||||
for _ in range(21):
|
||||
decision, release = limiter.admit(b'heavy')
|
||||
self.assertTrue(decision.allowed)
|
||||
release()
|
||||
releases = []
|
||||
for number in range(7):
|
||||
decision, release = limiter.admit(bytes([number]))
|
||||
self.assertTrue(decision.allowed)
|
||||
releases.append(release)
|
||||
decision, _ = limiter.admit(b'heavy')
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual(decision.limit, 20)
|
||||
decision, release = limiter.admit(b'light')
|
||||
self.assertTrue(decision.allowed)
|
||||
release()
|
||||
release()
|
||||
for release in releases:
|
||||
release()
|
||||
decision, release = limiter.admit(b'heavy')
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual(decision.limit, 40)
|
||||
release()
|
||||
self.assertEqual(limiter.inflight, 0)
|
||||
|
||||
def test_state_is_bounded_and_rolling_window_expires(self):
|
||||
now = [100.0]
|
||||
limiter = AdaptiveLimiter(rpm=2, fair_rpm=1, max_inflight=2,
|
||||
per_key_inflight=1, max_keys=2, clock=lambda: now[0])
|
||||
for _ in range(2):
|
||||
_, release = limiter.admit(b'a')
|
||||
release()
|
||||
decision, _ = limiter.admit(b'a')
|
||||
self.assertEqual((decision.status, decision.retry_after), (429, 60))
|
||||
_, release = limiter.admit(b'b')
|
||||
decision, _ = limiter.admit(b'c')
|
||||
self.assertEqual(decision.status, 503)
|
||||
release()
|
||||
now[0] += 60
|
||||
decision, release = limiter.admit(b'c')
|
||||
self.assertTrue(decision.allowed)
|
||||
release()
|
||||
self.assertLessEqual(len(limiter.keys), 2)
|
||||
|
||||
def test_secondary_keys_share_identity_without_storing_credentials(self):
|
||||
limiter = AdaptiveLimiter()
|
||||
self.assertEqual(limiter.identity('main', 17), limiter.identity('secondary', 17))
|
||||
self.assertNotEqual(limiter.identity('main', 17), limiter.identity('main', 18))
|
||||
self.assertNotIn(b'main', limiter.identity('main'))
|
||||
|
||||
|
||||
class FeatureHTTPTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.api = str(Path(self.tmp.name) / 'api.db')
|
||||
self.bot = str(Path(self.tmp.name) / 'bot.db')
|
||||
with closing(sqlite3.connect(self.api)) as con, con:
|
||||
con.executescript('CREATE TABLE users(id INTEGER,status INTEGER,deleted_at INTEGER);'
|
||||
'INSERT INTO users VALUES(1,1,NULL);'
|
||||
'CREATE TABLE tokens(id INTEGER,name TEXT,status INTEGER,expired_time INTEGER,remain_quota INTEGER,'
|
||||
'unlimited_quota INTEGER,model_limits_enabled INTEGER,model_limits TEXT,user_id INTEGER,key TEXT,deleted_at INTEGER);'
|
||||
'INSERT INTO tokens VALUES(1,"tg17",1,-1,10000,0,1,"exact-model",1,"main",NULL);'
|
||||
'INSERT INTO tokens VALUES(2,"pm17-k1",1,-1,10000,0,1,"exact-model",1,"extra",NULL);')
|
||||
with closing(sqlite3.connect(self.bot)) as con, con:
|
||||
con.executescript('CREATE TABLE users(tg_id INTEGER,banned INTEGER,api_blocked INTEGER,api_block_reason TEXT,'
|
||||
'chat_count INTEGER,quota_date TEXT,rank_cache INTEGER);'
|
||||
'INSERT INTO users VALUES(17,0,0,NULL,1,NULL,1);')
|
||||
self.forwarded = []
|
||||
async def handler(request):
|
||||
self.forwarded.append(await request.read())
|
||||
if request.query.get('daily'):
|
||||
return web.json_response({'error': {'code': 'daily_limit', 'message': 'Daily limit'}}, status=429)
|
||||
if request.query.get('error'):
|
||||
return web.json_response({'error': {'code': 'local_failure', 'message': 'Failure'}}, status=503)
|
||||
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
await response.write(b'event: message_start\ndata: {"model":"exact-model","text":"opaque"}\n\n')
|
||||
await response.write_eof()
|
||||
return response
|
||||
app = web.Application()
|
||||
self.limiter = install(app, newapi_db=self.api, bot_db=self.bot, limits={1: 5000},
|
||||
limiter=AdaptiveLimiter(rpm=2, fair_rpm=1, max_inflight=2, per_key_inflight=1))
|
||||
app.router.add_route('*', '/{tail:.*}', handler)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self):
|
||||
await self.client.close()
|
||||
self.tmp.cleanup()
|
||||
|
||||
async def request(self, key='main', path='/v1/messages', body=b'{"model":"exact-model", "stream": true}'):
|
||||
return await self.client.post(path, data=body, headers={'X-Api-Key': key, 'Content-Type': 'application/json'})
|
||||
|
||||
async def test_daily_headers_and_exact_body_sse_for_both_protocols(self):
|
||||
payload = b'{"model":"exact-model", "stream": true}'
|
||||
for path in ('/v1/messages', '/v1/chat/completions'):
|
||||
response = await self.request(path=path, body=payload)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.headers['X-Iishko-Daily-Limit'], '5000')
|
||||
self.assertEqual(response.headers['X-Gateway-Status'], 'operational')
|
||||
self.assertEqual(len(response.headers['X-Request-ID']), 32)
|
||||
self.assertEqual(await response.read(), b'event: message_start\ndata: {"model":"exact-model","text":"opaque"}\n\n')
|
||||
self.assertEqual(self.forwarded, [payload, payload])
|
||||
self.assertEqual(self.limiter.inflight, 0)
|
||||
|
||||
async def test_account_shared_rpm_and_early_denials_never_forward(self):
|
||||
for key in ('main', 'extra'):
|
||||
response = await self.request(key=key)
|
||||
await response.read()
|
||||
response = await self.request(key='extra')
|
||||
self.assertEqual(response.status, 429)
|
||||
self.assertEqual((await response.json())['error']['code'], 'adaptive_rate_limit')
|
||||
self.assertGreater(int(response.headers['Retry-After']), 0)
|
||||
self.assertEqual(len(self.forwarded), 2)
|
||||
|
||||
async def test_invalid_key_and_forbidden_model_are_not_admitted(self):
|
||||
response = await self.request(key='unknown')
|
||||
self.assertEqual(response.status, 401)
|
||||
response = await self.request(body=b'{"model":"foreign"}')
|
||||
self.assertEqual(response.status, 403)
|
||||
self.assertEqual(len(self.forwarded), 0)
|
||||
self.assertEqual(self.limiter.inflight, 0)
|
||||
|
||||
async def test_error_body_length_and_correlation_match_wire_payload(self):
|
||||
response = await self.request(path='/v1/messages?error=1')
|
||||
body = await response.read()
|
||||
self.assertEqual(int(response.headers['Content-Length']), len(body))
|
||||
payload = await response.json()
|
||||
self.assertEqual(payload['error']['request_id'], response.headers['X-Request-ID'])
|
||||
self.assertEqual(payload['error']['gateway_status'], 'degraded')
|
||||
|
||||
async def test_declared_content_type_cannot_skip_the_model_gate(self):
|
||||
for content_type in ('application/octet-stream', 'text/plain'):
|
||||
with self.subTest(content_type=content_type):
|
||||
response = await self.client.post('/v1/messages', data=b'{"model":"foreign"}',
|
||||
headers={'X-Api-Key': 'main', 'Content-Type': content_type})
|
||||
self.assertEqual(response.status, 403)
|
||||
self.assertEqual((await response.json())['error']['code'], 'model_access_denied')
|
||||
self.assertEqual(self.forwarded, [])
|
||||
allowed = await self.client.post('/v1/messages', data=b'{"model":"exact-model"}',
|
||||
headers={'X-Api-Key': 'main', 'Content-Type': 'application/octet-stream'})
|
||||
self.assertEqual(allowed.status, 200)
|
||||
await allowed.read()
|
||||
self.assertEqual(self.forwarded, [b'{"model":"exact-model"}'])
|
||||
|
||||
async def test_json_generation_requires_a_model_before_forwarding(self):
|
||||
for body, content_type in ((b'{"stream": true}', 'application/json'),
|
||||
(b'{"model": ""}', 'application/json'),
|
||||
(b'{"model": 5}', 'application/octet-stream')):
|
||||
with self.subTest(body=body):
|
||||
response = await self.client.post('/v1/messages', data=body,
|
||||
headers={'X-Api-Key': 'main', 'Content-Type': content_type})
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual((await response.json())['error']['code'], 'invalid_request')
|
||||
self.assertEqual(self.forwarded, [])
|
||||
|
||||
async def test_multipart_model_is_read_without_consuming_the_upload_body(self):
|
||||
boundary = 'X-TEST-BOUNDARY'
|
||||
body = (b'--' + boundary.encode() + b'\r\nContent-Disposition: form-data; name="model"\r\n\r\nexact-model\r\n'
|
||||
b'--' + boundary.encode() + b'\r\nContent-Disposition: form-data; name="file"; filename="a.wav"\r\n'
|
||||
b'Content-Type: audio/wav\r\n\r\n' + b'x' * 64 + b'\r\n--' + boundary.encode() + b'--\r\n')
|
||||
response = await self.client.post('/v1/audio/transcriptions', data=body,
|
||||
headers={'X-Api-Key': 'main',
|
||||
'Content-Type': 'multipart/form-data; boundary=' + boundary})
|
||||
self.assertEqual(response.status, 200)
|
||||
await response.read()
|
||||
self.assertEqual(self.forwarded, [body])
|
||||
|
||||
async def test_daily_limit_429_carries_moscow_reset_without_overriding_adaptive_delay(self):
|
||||
response = await self.request(path='/v1/messages?daily=1')
|
||||
self.assertEqual(response.status, 429)
|
||||
payload = await response.json()
|
||||
self.assertEqual(payload['error']['code'], 'daily_limit')
|
||||
now = int(time.time())
|
||||
moment = datetime.fromtimestamp(now, MSK)
|
||||
reset = int(datetime.combine(moment.date() + timedelta(days=1), datetime.min.time(), MSK).timestamp())
|
||||
self.assertLessEqual(abs(int(response.headers['Retry-After']) - max(1, reset - now)), 2)
|
||||
second = await self.request(path='/v1/messages?daily=1')
|
||||
self.assertEqual(second.status, 429)
|
||||
await second.read()
|
||||
adaptive = await self.request(path='/v1/messages?daily=1')
|
||||
self.assertEqual(adaptive.status, 429)
|
||||
payload = await adaptive.json()
|
||||
self.assertEqual(payload['error']['code'], 'adaptive_rate_limit')
|
||||
self.assertLessEqual(int(adaptive.headers['Retry-After']), 60)
|
||||
|
||||
async def test_credential_failure_never_reads_the_generation_body(self):
|
||||
forwarded = []
|
||||
async def handler(request):
|
||||
forwarded.append(await request.read())
|
||||
return web.json_response({'ok': True})
|
||||
app = web.Application(client_max_size=64)
|
||||
install(app, newapi_db=self.api, bot_db=self.bot, limits={1: 5000})
|
||||
app.router.add_route('*', '/{tail:.*}', handler)
|
||||
client = TestClient(TestServer(app))
|
||||
await client.start_server()
|
||||
try:
|
||||
oversized = b'{"model":"exact-model","pad":"' + b'x' * 200 + b'"}'
|
||||
denied = await client.post('/v1/messages', data=oversized,
|
||||
headers={'X-Api-Key': 'unknown', 'Content-Type': 'application/json'})
|
||||
self.assertEqual(denied.status, 401)
|
||||
await denied.read()
|
||||
self.assertEqual(forwarded, [])
|
||||
authenticated = await client.post('/v1/messages', data=oversized,
|
||||
headers={'X-Api-Key': 'main', 'Content-Type': 'application/json'})
|
||||
self.assertEqual(authenticated.status, 413)
|
||||
await authenticated.read()
|
||||
self.assertEqual(forwarded, [])
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,129 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway' if (ROOT / 'gateway').is_dir() else ROOT))
|
||||
from gateway_provider_relay import relay_selected
|
||||
from gateway_providers import ProviderChoice, ProviderRegistry, ProviderError
|
||||
|
||||
|
||||
class Registry:
|
||||
def __init__(self):
|
||||
self.choices, self.completed, self.abandoned = [], [], []
|
||||
def choose(self, db, key, model, *, pinned=None, effort=None, exclude=()):
|
||||
identity = pinned or ('reserve' if exclude else 'primary')
|
||||
choice = ProviderChoice(identity, 2 if identity == 'reserve' else 1, model)
|
||||
self.choices.append(choice)
|
||||
return choice
|
||||
def complete(self, choice, status, **kwargs):
|
||||
self.completed.append((choice.id, status))
|
||||
def abandon(self, choice):
|
||||
self.abandoned.append(choice.id)
|
||||
pinned_authorization = staticmethod(ProviderRegistry.pinned_authorization)
|
||||
|
||||
|
||||
class ProviderRelayTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.calls = []
|
||||
self.first_status = 503
|
||||
self.first_body = b'{"error":{"code":"upstream_throttled"}}'
|
||||
self.registry = Registry()
|
||||
self.wire_body = b'{ "model": "exact-model", "stream": true, "tools": [] }'
|
||||
self.wire_reply = b'event: content_block_delta\ndata: {"delta":{"text":"exact bytes"}}\n\n'
|
||||
async def upstream(request):
|
||||
self.calls.append((request.headers.get('Authorization'), await request.read()))
|
||||
if len(self.calls) == 1 and self.first_status >= 400:
|
||||
return web.Response(status=self.first_status, body=self.first_body, content_type='application/json')
|
||||
return web.Response(body=self.wire_reply, content_type='text/event-stream')
|
||||
app = web.Application()
|
||||
app.router.add_post('/v1/messages', upstream)
|
||||
self.upstream = TestServer(app)
|
||||
await self.upstream.start_server()
|
||||
self.session = aiohttp.ClientSession()
|
||||
async def gateway(request):
|
||||
async def success(response):
|
||||
if request.headers.get('X-Test-Stream-Failure'):
|
||||
raise aiohttp.ClientPayloadError('stream interrupted')
|
||||
return web.Response(body=await response.read(), headers={'Content-Type': response.headers['Content-Type']})
|
||||
async def failure(status, raw, headers):
|
||||
return web.Response(status=status, body=raw, content_type='application/json')
|
||||
try:
|
||||
return await relay_selected(request, self.session, self.upstream.make_url('/v1/messages'),
|
||||
headers=request.headers, body=await request.read(), registry=self.registry,
|
||||
newapi_db='unused', raw_key='testkey', model='exact-model',
|
||||
success=success, failure=failure)
|
||||
except ProviderError as error:
|
||||
return web.json_response({'error': {'code': error.code}}, status=error.status)
|
||||
app = web.Application()
|
||||
app.router.add_post('/v1/messages', gateway)
|
||||
self.client = TestClient(TestServer(app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self):
|
||||
await self.client.close()
|
||||
await self.session.close()
|
||||
await self.upstream.close()
|
||||
|
||||
async def request(self, **headers):
|
||||
return await self.client.post('/v1/messages', data=self.wire_body,
|
||||
headers={'Content-Type': 'application/json', **headers})
|
||||
|
||||
async def test_explicit_overload_falls_back_once_with_exact_model_and_payload(self):
|
||||
response = await self.request()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(await response.read(), self.wire_reply)
|
||||
self.assertEqual(self.calls, [('Bearer sk-testkey-1', self.wire_body),
|
||||
('Bearer sk-testkey-2', self.wire_body)])
|
||||
self.assertEqual(self.registry.completed, [('primary', 503), ('reserve', 200)])
|
||||
|
||||
async def test_pinned_provider_is_not_silently_replaced(self):
|
||||
response = await self.request(**{'X-Iishko-Provider': 'primary'})
|
||||
self.assertEqual(response.status, 503)
|
||||
await response.read()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
async def test_unknown_failure_and_billing_error_are_never_replayed(self):
|
||||
self.first_body = b'{"error":{"code":"insufficient_quota"}}'
|
||||
response = await self.request()
|
||||
self.assertEqual(response.status, 503)
|
||||
await response.read()
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
async def test_successful_headers_followed_by_stream_error_never_replay(self):
|
||||
self.first_status = 200
|
||||
with self.assertRaises(aiohttp.ServerDisconnectedError):
|
||||
await self.request(**{'X-Test-Stream-Failure': '1'})
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
self.assertEqual(len(self.registry.choices), 1)
|
||||
self.assertEqual(self.registry.completed, [('primary', 502)])
|
||||
|
||||
async def test_header_effort_does_not_silently_rewrite_generation_body(self):
|
||||
response = await self.request(**{'X-Iishko-Effort': 'high'})
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual((await response.json())['error']['code'], 'effort_requires_request_field')
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
async def test_ambiguous_transport_error_is_not_retried(self):
|
||||
class BrokenSession:
|
||||
def request(self, *args, **kwargs):
|
||||
raise aiohttp.ClientConnectionError('ambiguous connection failure')
|
||||
request = Mock(method='POST', headers={}, transport=Mock())
|
||||
request.__getitem__ = Mock()
|
||||
failure = Mock(side_effect=lambda *args: asyncio.sleep(0, result=args[0]))
|
||||
result = await relay_selected(request, BrokenSession(), 'http://unused/', headers={},
|
||||
body=self.wire_body, registry=self.registry, newapi_db='unused',
|
||||
raw_key='testkey', model='exact-model', success=Mock(), failure=failure)
|
||||
self.assertEqual(result, 503)
|
||||
self.assertEqual(len(self.registry.choices), 1)
|
||||
self.assertEqual(self.registry.completed, [('primary', 502)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,216 @@
|
||||
from contextlib import closing
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1]))
|
||||
from gateway_providers import ProviderError, ProviderRegistry, response_effort, safe_to_retry
|
||||
|
||||
|
||||
def configuration():
|
||||
return {"pinning_enabled": True, "providers": [
|
||||
{"id": "primary", "name": "Primary", "channel_ids": [1], "max_inflight": 1,
|
||||
"models": {"exact-model": {"effort_levels": ["low", "high"]}}},
|
||||
{"id": "reserve", "name": "Reserve", "channel_ids": [2], "reserve": True,
|
||||
"models": {"exact-model": {"effort_levels": None}}}]}
|
||||
|
||||
|
||||
class ProviderTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.db = str(Path(self.tmp.name) / "newapi.db")
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.executescript('CREATE TABLE users(id INTEGER PRIMARY KEY,role INTEGER,status INTEGER,deleted_at INTEGER);'
|
||||
'CREATE TABLE tokens(key TEXT,user_id INTEGER,"group" TEXT,status INTEGER,deleted_at INTEGER);'
|
||||
'CREATE TABLE channels(id INTEGER PRIMARY KEY,status INTEGER,model_mapping TEXT);'
|
||||
'CREATE TABLE abilities(channel_id INTEGER,model TEXT,enabled INTEGER,"group" TEXT);')
|
||||
con.execute('INSERT INTO users VALUES(1,100,1,NULL)')
|
||||
con.execute('INSERT INTO tokens VALUES("testkey",1,"default",1,NULL)')
|
||||
con.executemany('INSERT INTO channels VALUES(?,1,"{}")', [(1,), (2,)])
|
||||
con.executemany('INSERT INTO abilities VALUES(?,"exact-model",1,"default")', [(1,), (2,)])
|
||||
self.now = [1000.0]
|
||||
self.registry = ProviderRegistry(configuration(), clock=lambda: self.now[0])
|
||||
|
||||
def test_primary_reserves_capacity_and_routes_busy_requests_to_same_model_reserve(self):
|
||||
first = self.registry.choose(self.db, "testkey", "exact-model")
|
||||
second = self.registry.choose(self.db, "testkey", "exact-model")
|
||||
self.assertEqual((first.id, second.id), ("primary", "reserve"))
|
||||
self.assertEqual(second.model, first.model)
|
||||
with self.assertRaises(ProviderError) as caught:
|
||||
self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.assertEqual(caught.exception.code, "no_healthy_provider")
|
||||
self.registry.complete(first, 200)
|
||||
recovered = self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.assertEqual(recovered.id, "primary")
|
||||
self.registry.abandon(recovered)
|
||||
self.registry.abandon(second)
|
||||
self.assertEqual(sum(self.registry._active.values()), 0)
|
||||
|
||||
def test_circuit_has_one_half_open_probe_and_recovers_only_after_success(self):
|
||||
for _ in range(3):
|
||||
choice = self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.registry.complete(choice, 503)
|
||||
with self.assertRaises(ProviderError):
|
||||
self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.now[0] += 15
|
||||
probe = self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.assertTrue(probe.probe)
|
||||
with self.assertRaises(ProviderError):
|
||||
self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.registry.complete(probe, 200)
|
||||
self.assertFalse(self.registry.choose(self.db, "testkey", "exact-model", pinned="primary").probe)
|
||||
|
||||
def test_cancelled_probe_releases_lease_without_claiming_success(self):
|
||||
for _ in range(3):
|
||||
self.registry.complete(self.registry.choose(self.db, "testkey", "exact-model", pinned="primary"), 503)
|
||||
self.now[0] += 15
|
||||
first = self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.registry.abandon(first)
|
||||
again = self.registry.choose(self.db, "testkey", "exact-model", pinned="primary")
|
||||
self.assertTrue(again.probe)
|
||||
self.registry.abandon(again)
|
||||
|
||||
def test_unknown_effort_is_not_advertised_as_supported_or_silently_ignored(self):
|
||||
snapshot = self.registry.catalog(self.db, "exact-model")
|
||||
self.assertIsNone(snapshot["providers"][1]["effort"])
|
||||
self.assertEqual(snapshot["providers"][0]["verification"]["status"], "unverified")
|
||||
with self.assertRaises(ProviderError) as caught:
|
||||
self.registry.choose(self.db, "testkey", "exact-model", pinned="reserve", effort="high")
|
||||
self.assertEqual(caught.exception.code, "effort_not_supported")
|
||||
self.assertNotIn("channel_id", json.dumps(snapshot))
|
||||
self.assertNotIn("testkey", json.dumps(snapshot))
|
||||
|
||||
def test_channel_mapping_or_group_cannot_bypass_exact_model(self):
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute('UPDATE channels SET model_mapping=? WHERE id=1', (json.dumps({"exact-model": "substitute"}),))
|
||||
con.execute('UPDATE abilities SET "group"="other" WHERE channel_id=2')
|
||||
with self.assertRaises(ProviderError):
|
||||
self.registry.choose(self.db, "testkey", "exact-model")
|
||||
self.assertFalse(any(item["available"] for item in self.registry.catalog(self.db, "exact-model")["providers"]))
|
||||
|
||||
def test_regular_newapi_user_or_disabled_channel_cannot_use_admin_pinning(self):
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.execute('UPDATE users SET role=1')
|
||||
with self.assertRaises(ProviderError) as caught:
|
||||
self.registry.choose(self.db, "testkey", "exact-model")
|
||||
self.assertEqual(caught.exception.code, "provider_selection_unavailable")
|
||||
|
||||
def test_pinning_is_opt_in_and_a_channel_cannot_fake_two_reserves(self):
|
||||
with self.assertRaises(ProviderError):
|
||||
ProviderRegistry().choose(self.db, "testkey", "exact-model")
|
||||
config = configuration()
|
||||
config["providers"][1]["channel_ids"] = [1]
|
||||
with self.assertRaises(ValueError):
|
||||
ProviderRegistry(config)
|
||||
|
||||
def test_verified_label_requires_evidence_and_does_not_accept_original_claim(self):
|
||||
config = configuration()
|
||||
cap = config["providers"][0]["models"]["exact-model"]
|
||||
cap["verification"] = {"status": "operator_verified", "method": "official_route"}
|
||||
with self.assertRaises(ValueError):
|
||||
ProviderRegistry(config)
|
||||
cap["verification"] = {"status": "original", "method": "response_model"}
|
||||
with self.assertRaises(ValueError):
|
||||
ProviderRegistry(config)
|
||||
|
||||
def test_verification_status_must_match_the_method_it_claims(self):
|
||||
config = configuration()
|
||||
reference = "private operator note: https://admin.internal/route/17?token=opaque"
|
||||
config["providers"][0]["models"]["exact-model"]["verification"] = {
|
||||
"status": "identity_checked", "method": "response_model",
|
||||
"checked_at": 1792950000, "reference": reference}
|
||||
registry = ProviderRegistry(config)
|
||||
snapshot = registry.catalog(self.db, "exact-model")
|
||||
self.assertEqual(snapshot["providers"][0]["verification"],
|
||||
{"status": "identity_checked", "method": "response_model",
|
||||
"checked_at": 1792950000})
|
||||
self.assertNotIn("admin.internal", json.dumps(snapshot))
|
||||
self.assertEqual(
|
||||
registry.providers[0]["models"]["exact-model"]["verification"]["reference"], reference)
|
||||
for broken in (
|
||||
{"status": "operator_verified", "method": "response_model",
|
||||
"checked_at": 1792950000, "reference": "note"},
|
||||
{"status": "identity_checked", "method": "official_route",
|
||||
"checked_at": 1792950000, "reference": "note"},
|
||||
{"status": "operator_verified", "method": "none",
|
||||
"checked_at": 1792950000, "reference": "note"},
|
||||
{"status": "unverified", "method": "none", "checked_at": 1792950000},
|
||||
{"status": "unverified", "method": "none", "reference": "note"},
|
||||
{"status": "identity_checked", "method": "response_model", "checked_at": 1792950000},
|
||||
{"status": "identity_checked", "method": "response_model",
|
||||
"checked_at": 1792950000, "reference": " "},
|
||||
{"status": "identity_checked", "method": "response_model",
|
||||
"checked_at": 1792950000, "reference": "x" * 201},
|
||||
{"status": "identity_checked", "method": "response_model",
|
||||
"checked_at": 1792950000, "reference": "note", "extra": "silently dropped"},
|
||||
{"status": "identity_checked", "method": [],
|
||||
"checked_at": 1792950000, "reference": "note"},
|
||||
{"status": "identity_checked", "method": {},
|
||||
"checked_at": 1792950000, "reference": "note"},
|
||||
):
|
||||
with self.subTest(broken=broken):
|
||||
config = configuration()
|
||||
config["providers"][0]["models"]["exact-model"]["verification"] = broken
|
||||
with self.assertRaises(ValueError):
|
||||
ProviderRegistry(config)
|
||||
|
||||
def test_verified_route_requires_operator_grade_evidence_and_keeps_reference_private(self):
|
||||
config = configuration()
|
||||
config["providers"][0]["models"]["exact-model"]["verification"] = {
|
||||
"status": "operator_verified", "method": "official_route",
|
||||
"checked_at": 1792950000, "reference": "ticket OPS-42"}
|
||||
registry = ProviderRegistry(config)
|
||||
snapshot = registry.catalog(self.db, "exact-model")
|
||||
self.assertEqual(snapshot["providers"][0]["verification"]["status"], "operator_verified")
|
||||
self.assertNotIn("OPS-42", json.dumps(snapshot))
|
||||
|
||||
def test_shipped_example_configuration_matches_the_validator(self):
|
||||
example = Path(__file__).resolve().parents[1] / "gateway" / "providers.example.json"
|
||||
registry = ProviderRegistry.from_file(str(example))
|
||||
self.assertFalse(registry.pinning_enabled)
|
||||
reserve = next(p for p in registry.providers if p["id"] == "example-reserve")
|
||||
verification = reserve["models"]["example-model"]["verification"]
|
||||
self.assertEqual((verification["status"], verification["method"]),
|
||||
("identity_checked", "response_model"))
|
||||
self.assertTrue(verification["reference"])
|
||||
|
||||
def test_effort_metadata_is_read_consistently_without_mutating_payload(self):
|
||||
body = {"model": "exact-model", "reasoning_effort": "high", "reasoning": {"effort": "high"}}
|
||||
original = json.dumps(body)
|
||||
self.assertEqual(response_effort(body), "high")
|
||||
self.assertEqual(json.dumps(body), original)
|
||||
body["reasoning"]["effort"] = "low"
|
||||
with self.assertRaises(ProviderError):
|
||||
response_effort(body)
|
||||
|
||||
def test_effort_optional_nulls_do_not_reject_ordinary_openai_requests(self):
|
||||
self.assertIsNone(response_effort({"reasoning_effort": None}))
|
||||
self.assertIsNone(response_effort({"reasoning": {"effort": None}}))
|
||||
self.assertEqual(response_effort({"reasoning_effort": None,
|
||||
"reasoning": {"effort": "high"}}), "high")
|
||||
|
||||
def test_misplaced_effort_is_rejected_instead_of_silently_ignored(self):
|
||||
for body in ({"effort": "high"}, {"effort": "high", "reasoning_effort": "high"}):
|
||||
with self.subTest(body=body), self.assertRaises(ProviderError) as caught:
|
||||
response_effort(body)
|
||||
self.assertEqual(caught.exception.code, "invalid_effort")
|
||||
|
||||
def test_vendor_effort_is_preserved_and_malformed_values_are_rejected(self):
|
||||
self.assertEqual(response_effort({"output_config": {"effort": "max"}}), "max")
|
||||
for value in ("", 1, True, [], {}, "x" * 33):
|
||||
with self.subTest(value=value), self.assertRaises(ProviderError):
|
||||
response_effort({"reasoning_effort": value})
|
||||
|
||||
def test_only_explicit_overload_is_eligible_for_fallback(self):
|
||||
raw = json.dumps({"error": {"code": "upstream_throttled"}}).encode()
|
||||
self.assertTrue(safe_to_retry(429, raw))
|
||||
for status, body in ((502, raw), (504, raw), (503, b"unknown error"), (503, b'{"error":{"code":"insufficient_quota"}}')):
|
||||
self.assertFalse(safe_to_retry(status, body))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
from contextlib import closing
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1]))
|
||||
from gateway_usage import daily_snapshot, quota_headers
|
||||
|
||||
|
||||
class DailyUsageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.bot = str(Path(self.tmp.name) / "bot.db")
|
||||
self.api = str(Path(self.tmp.name) / "api.db")
|
||||
with closing(sqlite3.connect(self.bot)) as con, con:
|
||||
con.execute("CREATE TABLE users(tg_id INTEGER PRIMARY KEY,chat_count INTEGER,quota_date TEXT,rank_cache INTEGER,vip INTEGER,admin INTEGER,unlim_until INTEGER)")
|
||||
con.execute('INSERT INTO users VALUES(123,21,"2026-10-25",1,0,0,0)')
|
||||
with closing(sqlite3.connect(self.api)) as con, con:
|
||||
con.execute('CREATE TABLE tokens(name TEXT,key TEXT,deleted_at INTEGER)')
|
||||
con.executemany('INSERT INTO tokens VALUES(?,?,NULL)', [('tg123','main'),('pm123','promo'),('sol123-k2','extra'),('tg123other','foreign')])
|
||||
self.now = int(datetime(2026,10,25,20,59,59,tzinfo=timezone.utc).timestamp())
|
||||
|
||||
def test_shared_usage_is_read_only_and_consistent_across_key_families(self):
|
||||
snapshots = [daily_snapshot(self.api,self.bot,key,now=self.now) for key in ('main','promo','extra')]
|
||||
self.assertEqual(snapshots[0], snapshots[1])
|
||||
self.assertEqual(snapshots[1], snapshots[2])
|
||||
self.assertEqual(snapshots[0]['remaining'], 4979)
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
self.assertEqual(con.execute('SELECT chat_count FROM users').fetchone()[0],21)
|
||||
self.assertIsNone(daily_snapshot(self.api,self.bot,'foreign',now=self.now))
|
||||
self.assertIsNone(daily_snapshot(self.api,self.bot,'unknown',now=self.now))
|
||||
|
||||
def test_reset_is_moscow_midnight_not_utc_and_stale_usage_does_not_leak(self):
|
||||
before = daily_snapshot(self.api,self.bot,'main',now=self.now)
|
||||
self.assertEqual(before['reset_at'], self.now+1)
|
||||
after = daily_snapshot(self.api,self.bot,'main',now=self.now+1)
|
||||
self.assertEqual(after['used'],0)
|
||||
self.assertEqual(after['date'],'2026-10-26')
|
||||
self.assertEqual(after['reset_at'],self.now+1+86400)
|
||||
|
||||
def test_purchased_extra_requests_extend_limit_not_rank(self):
|
||||
reader=lambda db,uid,now=None: {'extra_requests':100}
|
||||
data=daily_snapshot(self.api,self.bot,'main',now=self.now,entitlement_reader=reader)
|
||||
self.assertEqual((data['limit'],data['remaining']),(5100,5079))
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
self.assertEqual(con.execute('SELECT rank_cache FROM users').fetchone()[0],1)
|
||||
|
||||
def test_headers_are_out_of_band_and_unlimited_is_not_a_fake_zero(self):
|
||||
with closing(sqlite3.connect(self.bot)) as con, con:
|
||||
con.execute('UPDATE users SET vip=1')
|
||||
data=daily_snapshot(self.api,self.bot,'main',now=self.now)
|
||||
self.assertIsNone(data['limit'])
|
||||
self.assertIsNone(data['remaining'])
|
||||
headers=quota_headers(data)
|
||||
self.assertEqual(headers['X-Iishko-Daily-Remaining'],'unlimited')
|
||||
self.assertEqual(headers['X-Iishko-Daily-Scope'],'account')
|
||||
self.assertEqual(quota_headers(None),{})
|
||||
|
||||
def test_broken_counter_schema_is_explicit_failure_not_zero_or_unlimited(self):
|
||||
with closing(sqlite3.connect(self.bot)) as con, con:
|
||||
con.execute('ALTER TABLE users RENAME COLUMN chat_count TO old_count')
|
||||
with self.assertRaises(sqlite3.DatabaseError):
|
||||
daily_snapshot(self.api,self.bot,'main',now=self.now)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Execute actual HTTP handlers, without production startup side effects."""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from aiohttp import web
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def namespace(names, **dependencies):
|
||||
tree = ast.parse((ROOT / 'bot' / 'webapp' / 'server.py').read_text(encoding='utf-8'))
|
||||
found = {node.name: node for node in tree.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||
body = []
|
||||
for name in names:
|
||||
node = found[name]
|
||||
node.decorator_list = []
|
||||
body.append(node)
|
||||
env = {'asyncio': asyncio, 'sqlite3': sqlite3, 'web': web,
|
||||
'log': logging.getLogger('http-contract'),
|
||||
'BOT_DB': '/temporary/bot.db', 'NEWAPI_DB': '/temporary/gateway.db',
|
||||
**dependencies}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=body, type_ignores=[])),
|
||||
'<actual-server-handlers>', 'exec'), env)
|
||||
return env
|
||||
|
||||
|
||||
class RankingHTTPTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_all_kinds_forward_query_and_execute_off_event_loop(self):
|
||||
loop_thread = threading.get_ident()
|
||||
for kind in ('referrals', 'requests', 'tokens', 'models'):
|
||||
calls = []
|
||||
def top(*args):
|
||||
calls.append((args, threading.get_ident()))
|
||||
return {'top': [{'pos': 1, 'value': 123}], 'kind': kind}
|
||||
env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top))
|
||||
response = await env['api_top'](SimpleNamespace(query={
|
||||
'kind': kind, 'period': 'week', 'limit': '12'}))
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(json.loads(response.body)['kind'], kind)
|
||||
self.assertEqual(calls[0][0], ('/temporary/bot.db', '/temporary/gateway.db',
|
||||
kind, 'week', None, '12'))
|
||||
self.assertNotEqual(calls[0][1], loop_thread)
|
||||
|
||||
async def test_legacy_default_is_not_replaced_with_other_metric(self):
|
||||
calls = []
|
||||
def top(*args):
|
||||
calls.append(args)
|
||||
return {'top': [], 'kind': 'referrals', 'period': 'all'}
|
||||
env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top))
|
||||
response = await env['api_top'](SimpleNamespace(query={}))
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(calls[0][2:], (None, None, None, None))
|
||||
|
||||
async def test_bad_parameter_is_400(self):
|
||||
def top(*_args):
|
||||
raise ValueError('invalid kind')
|
||||
env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top))
|
||||
response = await env['api_top'](SimpleNamespace(query={'kind': 'malformed'}))
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual(json.loads(response.body)['error'], 'bad_request')
|
||||
|
||||
async def test_busy_is_503_not_success_with_empty_leaderboard(self):
|
||||
def top(*_args):
|
||||
raise sqlite3.OperationalError('database is locked')
|
||||
env = namespace(['_db_busy', 'api_top'], rankings=SimpleNamespace(top=top))
|
||||
with self.assertLogs('http-contract', level='ERROR'):
|
||||
response = await env['api_top'](SimpleNamespace(query={'kind': 'tokens'}))
|
||||
self.assertEqual(response.status, 503)
|
||||
data = json.loads(response.body)
|
||||
self.assertEqual(data['error'], 'db_busy')
|
||||
self.assertNotIn('top', data)
|
||||
|
||||
async def test_live_routes_point_to_active_handlers(self):
|
||||
tree = ast.parse((ROOT / 'bot/webapp/server.py').read_text(encoding='utf-8'))
|
||||
routes = {}
|
||||
for node in ast.walk(tree):
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
||||
and node.func.attr in ('add_get', 'add_post') and len(node.args) >= 2
|
||||
and isinstance(node.args[0], ast.Constant) and isinstance(node.args[1], ast.Name)):
|
||||
routes[(node.func.attr, node.args[0].value)] = node.args[1].id
|
||||
self.assertEqual(routes[('add_get', '/api/top')], 'api_top')
|
||||
self.assertEqual(routes[('add_get', '/api/bonus')], 'api_bonus')
|
||||
self.assertEqual(routes[('add_post', '/api/daily')], 'api_daily')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,265 @@
|
||||
import ast
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import closing
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
import types
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = Path(os.environ.get('IISHKO_KEYS_TEST_SOURCE', ROOT / 'bot/webapp/mk_daemon.py'))
|
||||
Q = 500_000
|
||||
UID = 12345
|
||||
|
||||
|
||||
def load_worker(gateway, bot):
|
||||
source = SOURCE.read_text(encoding='utf-8')
|
||||
tree = ast.parse(source, filename=str(SOURCE))
|
||||
# Execute production definitions, not its bot/network bootstrap or stdin loop.
|
||||
definitions = ast.Module(body=[n for n in tree.body if isinstance(
|
||||
n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))], type_ignores=[])
|
||||
spec = importlib.util.spec_from_file_location('quota_test_accounts', ROOT / 'bot/account_limits.py')
|
||||
accounts = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(accounts)
|
||||
ns = dict(asyncio=__import__('asyncio'), closing=closing, Path=Path, hashlib=hashlib,
|
||||
json=json, math=math, os=os, re=re, secrets=secrets, sqlite3=sqlite3,
|
||||
sys=__import__('sys'), time=time, GW_DB=str(gateway), BOT_DB=str(bot), Q=Q,
|
||||
account_uid=accounts.account_uid, account_token_names=accounts.account_token_names)
|
||||
exec(compile(definitions, str(SOURCE), 'exec'), ns)
|
||||
ns['_read_pause_state'] = lambda: {}
|
||||
return ns
|
||||
|
||||
|
||||
class KeyQuotaRecoveryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.directory.cleanup)
|
||||
self.gateway = Path(self.directory.name) / 'gateway.db'
|
||||
self.bot = Path(self.directory.name) / 'bot.db'
|
||||
with closing(sqlite3.connect(self.gateway)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE tokens (
|
||||
id INTEGER PRIMARY KEY, name TEXT, key TEXT, remain_quota INTEGER,
|
||||
status INTEGER DEFAULT 1, unlimited_quota INTEGER DEFAULT 0,
|
||||
expired_time INTEGER DEFAULT -1, deleted_at INTEGER);
|
||||
INSERT INTO tokens(id,name,key,remain_quota) VALUES
|
||||
(1,'tg12345','synthetic-main',100000000),
|
||||
(2,'tg12345-k1','synthetic-extra',50000000);
|
||||
''')
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
con.executescript('''
|
||||
CREATE TABLE users (tg_id INTEGER PRIMARY KEY, banned INTEGER DEFAULT 0,
|
||||
api_blocked INTEGER DEFAULT 0, token_name TEXT, api_key TEXT,
|
||||
key_locked INTEGER DEFAULT 0, cap_paused INTEGER DEFAULT 0);
|
||||
INSERT INTO users(tg_id,token_name,api_key) VALUES
|
||||
(12345,'tg12345','sk-synthetic-main');
|
||||
CREATE TABLE econ_tx (src INTEGER,dst INTEGER,units INTEGER,type TEXT,ts INTEGER);
|
||||
''')
|
||||
self.worker = load_worker(self.gateway, self.bot)
|
||||
with closing(self.worker['_connect']()):
|
||||
pass
|
||||
|
||||
def change(self, sql, params=()):
|
||||
with closing(sqlite3.connect(self.gateway)) as con:
|
||||
con.execute(sql, params)
|
||||
con.commit()
|
||||
|
||||
def bot_change(self, sql, params=()):
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
con.execute(sql, params)
|
||||
con.commit()
|
||||
|
||||
def state(self):
|
||||
with closing(sqlite3.connect(self.gateway)) as con:
|
||||
tokens = con.execute('SELECT id,remain_quota,status,deleted_at FROM tokens ORDER BY id').fetchall()
|
||||
receipts = con.execute('SELECT uid,request_id,digest,result FROM wa_key_operations ORDER BY request_id').fetchall()
|
||||
with closing(sqlite3.connect(self.bot)) as con:
|
||||
ledger = con.execute('SELECT * FROM econ_tx').fetchall()
|
||||
users = con.execute('SELECT * FROM users').fetchall()
|
||||
return tokens, receipts, ledger, users
|
||||
|
||||
def mutate(self, action='transfer', request_id='synthetic-request-0001', **params):
|
||||
return self.worker['mutate'](action, UID, request_id, **params)
|
||||
|
||||
def assert_rejected_unchanged(self, **params):
|
||||
before = self.state()
|
||||
with self.assertRaises(self.worker['KeyErrorSafe']):
|
||||
self.mutate(**params)
|
||||
self.assertEqual(before, self.state())
|
||||
|
||||
def test_topup_exhausted_reactivates_without_creating_quota(self):
|
||||
self.change('UPDATE tokens SET status=4,remain_quota=0 WHERE id=2')
|
||||
before = sum(r[1] for r in self.state()[0])
|
||||
result = self.mutate(n=1, usd=100, direction='to')
|
||||
rows, receipts, ledger, _ = self.state()
|
||||
self.assertEqual(result['moved_usd'], 100)
|
||||
self.assertEqual(rows[1][1:3], (100 * Q, 1))
|
||||
self.assertEqual(sum(r[1] for r in rows), before)
|
||||
self.assertEqual(len(receipts), 1)
|
||||
self.assertEqual(len(ledger), 1)
|
||||
|
||||
def test_refund_funded_exhausted_key(self):
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
before = sum(r[1] for r in self.state()[0])
|
||||
result = self.mutate(n=1, usd=0, direction='from')
|
||||
rows = self.state()[0]
|
||||
self.assertEqual(result['moved_usd'], 100)
|
||||
self.assertEqual(rows[1][1], 0)
|
||||
self.assertEqual(sum(r[1] for r in rows), before)
|
||||
|
||||
def test_partial_refund_reactivates_remaining_exhausted_balance(self):
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
self.mutate(n=1, usd=10, direction='from')
|
||||
self.assertEqual(self.state()[0][1][1:3], (90 * Q, 1))
|
||||
|
||||
def test_delete_exhausted_refunds_and_replays_once(self):
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
before = sum(r[1] for r in self.state()[0])
|
||||
first = self.mutate(action='del', n=1)
|
||||
after = self.state()
|
||||
self.assertEqual(after[0][1][1:3], (0, 2))
|
||||
self.assertIsNotNone(after[0][1][3])
|
||||
self.assertEqual(sum(r[1] for r in after[0]), before)
|
||||
self.assertEqual(first, self.mutate(action='del', n=1))
|
||||
self.assertEqual(after, self.state())
|
||||
|
||||
def test_refund_reactivates_exhausted_main(self):
|
||||
self.change('UPDATE tokens SET status=4,remain_quota=0 WHERE id=1')
|
||||
self.mutate(n=1, usd=0, direction='from')
|
||||
self.assertEqual(self.state()[0][0][1:3], (100 * Q, 1))
|
||||
|
||||
def test_disabled_expired_unknown_source_or_destination_stays_unchanged(self):
|
||||
for token in (1, 2):
|
||||
for status in (0, 2, 3, 99):
|
||||
with self.subTest(token=token, status=status):
|
||||
self.change('UPDATE tokens SET status=? WHERE id=?', (status, token))
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.change('UPDATE tokens SET status=1 WHERE id=?', (token,))
|
||||
|
||||
def test_expiration_timestamp_stays_fail_closed(self):
|
||||
for token in (1, 2):
|
||||
with self.subTest(token=token):
|
||||
self.change('UPDATE tokens SET expired_time=? WHERE id=?', (int(time.time()) - 1, token))
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.change('UPDATE tokens SET expired_time=-1 WHERE id=?', (token,))
|
||||
|
||||
def test_lock_evidence_prevents_exhausted_reactivation(self):
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
self.change("INSERT INTO wa_key_locks VALUES (2,12345,'tg12345-k1')")
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
|
||||
def test_daily_pause_evidence_prevents_exhausted_reactivation(self):
|
||||
self.change('CREATE TABLE wa_daily_cap_pauses(tid INTEGER,name TEXT)')
|
||||
self.change("INSERT INTO wa_daily_cap_pauses VALUES (2,'tg12345-k1')")
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
|
||||
def test_banned_or_api_blocked_account_stays_fail_closed(self):
|
||||
for column in ('banned', 'api_blocked'):
|
||||
with self.subTest(column=column):
|
||||
self.bot_change('UPDATE users SET ' + column + '=1')
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.bot_change('UPDATE users SET ' + column + '=0')
|
||||
|
||||
def test_inadequate_balance_and_unlimited_are_rejected(self):
|
||||
self.assert_rejected_unchanged(n=1, usd=1000, direction='to')
|
||||
for token in (1, 2):
|
||||
with self.subTest(token=token):
|
||||
self.change('UPDATE tokens SET unlimited_quota=1 WHERE id=?', (token,))
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.change('UPDATE tokens SET unlimited_quota=0 WHERE id=?', (token,))
|
||||
|
||||
def test_duplicate_extra_never_selects_arbitrary_balance_or_rewrites_main(self):
|
||||
self.change("INSERT INTO tokens(id,name,key,remain_quota) VALUES(3,'tg12345-k1','synthetic-duplicate',123)")
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='from')
|
||||
|
||||
def test_duplicate_main_is_disambiguated_only_by_exact_key(self):
|
||||
self.change("INSERT INTO tokens(id,name,key,remain_quota) VALUES(3,'tg12345','synthetic-duplicate',123)")
|
||||
self.mutate(n=1, usd=10, direction='to')
|
||||
self.assertEqual(self.state()[0][2][1], 123)
|
||||
self.bot_change("UPDATE users SET api_key='' ")
|
||||
self.assert_rejected_unchanged(request_id='synthetic-request-0002', n=1, usd=10, direction='to')
|
||||
|
||||
def test_foreign_pointer_and_missing_key_are_rejected(self):
|
||||
self.change("INSERT INTO tokens(id,name,key,remain_quota) VALUES(3,'tg67890','synthetic-foreign',123)")
|
||||
self.bot_change("UPDATE users SET api_key='sk-synthetic-foreign'")
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.bot_change("UPDATE users SET api_key='sk-synthetic-main'")
|
||||
self.assert_rejected_unchanged(n=2, usd=10, direction='to')
|
||||
|
||||
def test_reused_request_id_with_different_amount_is_rejected(self):
|
||||
self.mutate(n=1, usd=10, direction='to')
|
||||
self.assert_rejected_unchanged(n=1, usd=11, direction='to')
|
||||
|
||||
def test_parallel_replay_moves_quota_exactly_once(self):
|
||||
self.change('UPDATE tokens SET status=4,remain_quota=0 WHERE id=2')
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(lambda _: self.mutate(n=1, usd=10, direction='to'), range(4)))
|
||||
self.assertTrue(all(r == results[0] for r in results))
|
||||
rows, receipts, ledger, _ = self.state()
|
||||
self.assertEqual(rows[0][1], 190 * Q)
|
||||
self.assertEqual(rows[1][1:3], (10 * Q, 1))
|
||||
self.assertEqual(len(receipts), 1)
|
||||
self.assertEqual(len(ledger), 1)
|
||||
|
||||
def test_ledger_failure_rolls_back_balances_status_and_receipt(self):
|
||||
self.change('UPDATE tokens SET status=4,remain_quota=0 WHERE id=2')
|
||||
self.bot_change("CREATE TRIGGER deny_ledger BEFORE INSERT ON econ_tx BEGIN SELECT RAISE(ABORT,'synthetic ledger failure'); END")
|
||||
before = self.state()
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.mutate(n=1, usd=10, direction='to')
|
||||
self.assertEqual(before, self.state())
|
||||
|
||||
def test_account_pause_flags_block_topup_refund_and_delete(self):
|
||||
for flag in ('cap_paused', 'key_locked'):
|
||||
for status in (1, 4):
|
||||
with self.subTest(flag=flag, status=status):
|
||||
self.change('UPDATE tokens SET status=? WHERE id=2', (status,))
|
||||
self.bot_change('UPDATE users SET ' + flag + '=1')
|
||||
self.assert_rejected_unchanged(n=1, usd=10, direction='to')
|
||||
self.assert_rejected_unchanged(n=1, usd=0, direction='from')
|
||||
self.assert_rejected_unchanged(action='del', n=1)
|
||||
self.bot_change('UPDATE users SET ' + flag + '=0')
|
||||
|
||||
def test_zero_balance_delete_does_not_bypass_status_or_lock_checks(self):
|
||||
self.change('UPDATE tokens SET remain_quota=0 WHERE id=2')
|
||||
for status in (None, 0, 2, 3, 99):
|
||||
with self.subTest(status=status):
|
||||
self.change('UPDATE tokens SET status=? WHERE id=2', (status,))
|
||||
self.assert_rejected_unchanged(action='del', n=1)
|
||||
self.change('UPDATE tokens SET status=4 WHERE id=2')
|
||||
self.change("INSERT INTO wa_key_locks VALUES (2,12345,'tg12345-k1')")
|
||||
self.assert_rejected_unchanged(action='del', n=1)
|
||||
|
||||
def test_zero_balance_exhausted_delete_is_allowed_and_receipted_once(self):
|
||||
self.change('UPDATE tokens SET remain_quota=0,status=4 WHERE id=2')
|
||||
first = self.mutate(action='del', n=1)
|
||||
after = self.state()
|
||||
self.assertEqual(first['moved_usd'], 0)
|
||||
self.assertIsNotNone(after[0][1][3])
|
||||
self.assertEqual(first, self.mutate(action='del', n=1))
|
||||
self.assertEqual(after, self.state())
|
||||
self.assertEqual(len(after[1]), 1)
|
||||
self.assertEqual(len(after[2]), 1)
|
||||
|
||||
def test_null_destination_quota_receives_exact_credit(self):
|
||||
self.change('UPDATE tokens SET remain_quota=NULL,status=4 WHERE id=2')
|
||||
self.mutate(n=1, usd=10, direction='to')
|
||||
rows = self.state()[0]
|
||||
self.assertEqual(rows[0][1], 190 * Q)
|
||||
self.assertEqual(rows[1][1:3], (10 * Q, 1))
|
||||
self.assertEqual(sum(r[1] for r in rows), 200 * Q)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Presentation-only moderation badges must not change admission or routing."""
|
||||
import ast
|
||||
import copy
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import unittest
|
||||
|
||||
import model_advisories as advisory
|
||||
import public_catalogue
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EXPECTED = {
|
||||
"qwen3.8-max", "glm-5.3-prime", "kimi-k2.7-code", "qwen3-vl-plus",
|
||||
"qwen3.8-flash", "deepseek-v4.1-flash-1017", "kimi-k3.1-pro",
|
||||
"kimi-k3.1-pro-highspeed", "qwen-max", "qwen-plus", "deepseek-v4-pro",
|
||||
"glm-5.1", "kimi/kimi-k3.1-pro", "qwen3.8-max-0902",
|
||||
}
|
||||
|
||||
|
||||
class AdvisoryTests(unittest.TestCase):
|
||||
def test_exact_ids_and_explicit_scope(self):
|
||||
self.assertEqual(set(advisory.MODELS), EXPECTED)
|
||||
for name in EXPECTED:
|
||||
value = advisory.for_model(name)
|
||||
self.assertEqual(value["label"], "Строгая модерация провайдера")
|
||||
self.assertEqual(value["scope"], "some_provider_routes")
|
||||
self.assertIn("не означает недоступность", value["notice"])
|
||||
self.assertIn("может не помочь", value["notice"])
|
||||
self.assertNotIn("available", value)
|
||||
self.assertNotIn("configured", value)
|
||||
|
||||
def test_no_heuristic_alias_or_non_string_matching(self):
|
||||
for name in [None, [], {}, 1, "qwen-plus-unknown", "qwen-plus ", "gpt-6.1-sol"]:
|
||||
self.assertIsNone(advisory.for_model(name))
|
||||
|
||||
def test_returned_objects_do_not_mutate_shared_state(self):
|
||||
value = advisory.for_model("qwen-plus")
|
||||
value["label"] = "changed"
|
||||
self.assertEqual(advisory.for_model("qwen-plus")["label"], advisory.LABEL)
|
||||
|
||||
def test_actual_miniapp_enrichment_preserves_all_access_and_identity_fields(self):
|
||||
tree = ast.parse((ROOT / "bot/webapp/server.py").read_text(encoding="utf-8"))
|
||||
function = next(node for node in tree.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "api_models")
|
||||
loops = [node for node in function.body if isinstance(node, ast.For)
|
||||
and 'row[\'provider_moderation\']' in ast.unparse(node)]
|
||||
self.assertEqual(len(loops), 1)
|
||||
models = [{"name": name, "available": False, "min_rank": 4,
|
||||
"configured": False, "status": "down", "ms": 123}
|
||||
for name in ["qwen-plus", "gpt-6.1-sol"]]
|
||||
before = copy.deepcopy(models)
|
||||
scope = {"models": models, "provider_moderation_for_model": advisory.for_model}
|
||||
statements: list[ast.stmt] = list(loops)
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), "<actual enrichment>", "exec"), scope)
|
||||
for old, new in zip(before, models):
|
||||
self.assertEqual(old, {k: v for k, v in new.items() if k != "provider_moderation"})
|
||||
self.assertIsNotNone(models[0]["provider_moderation"])
|
||||
self.assertIsNone(models[1]["provider_moderation"])
|
||||
|
||||
def test_public_catalogue_preserves_configured_and_rank(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
source = root / "bot.py"
|
||||
source.write_text("TIER_MODELS = {1: [], 2: [], 3: [], 4: ['qwen-plus', 'gpt-6.1-sol']}\n"
|
||||
"MODEL_DESCS = {'qwen-plus': 'Example'}\n", encoding="utf-8")
|
||||
database = root / "gateway.db"
|
||||
with closing(sqlite3.connect(database)) as db, db:
|
||||
db.executescript("CREATE TABLE channels(id INTEGER,status INTEGER);"
|
||||
"CREATE TABLE abilities(channel_id INTEGER,model TEXT,enabled INTEGER);"
|
||||
"INSERT INTO channels VALUES(1,1);"
|
||||
"INSERT INTO abilities VALUES(1,'gpt-6.1-sol',1);")
|
||||
snapshot = public_catalogue.catalogue_snapshot(source, database, now=100)
|
||||
rows = {row["id"]: row for row in snapshot["models"]}
|
||||
self.assertFalse(rows["qwen-plus"]["configured"])
|
||||
self.assertEqual(rows["qwen-plus"]["min_rank"], 4)
|
||||
self.assertIsNotNone(rows["qwen-plus"]["provider_moderation"])
|
||||
self.assertTrue(rows["gpt-6.1-sol"]["configured"])
|
||||
self.assertIsNone(rows["gpt-6.1-sol"]["provider_moderation"])
|
||||
html = public_catalogue.render_catalogue(snapshot)
|
||||
self.assertEqual(html.count(advisory.LABEL), 1)
|
||||
self.assertIn(advisory.NOTICE, html)
|
||||
|
||||
def test_public_render_escapes_advisory(self):
|
||||
snapshot = {"models": [{"id": "test", "description": "", "min_rank": 1,
|
||||
"status": "unknown", "provider_moderation": {
|
||||
"label": '<img src=x onerror="alert(1)">',
|
||||
"notice": "<script>alert(1)</script>"}}]}
|
||||
html = public_catalogue.render_catalogue(snapshot)
|
||||
self.assertNotIn("<img", html)
|
||||
self.assertNotIn("<script>", html)
|
||||
self.assertIn("<script>", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Контракты единого каталога моделей (bot/model_catalogue.py).
|
||||
|
||||
Каталог — единственный источник правды для бота и Mini App. Литеральные
|
||||
проекции в bot/grok_bot.py и bot/webapp/server.py обязаны совпадать с модулем:
|
||||
именно их (без импорта бота) читают commerce_access.py и abilities_guard.py.
|
||||
"""
|
||||
import ast
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
BOT = ROOT / "bot" / "grok_bot.py"
|
||||
SERVER = ROOT / "bot" / "webapp" / "server.py"
|
||||
|
||||
import model_catalogue as cat
|
||||
|
||||
|
||||
def _literal_assigns(path, names):
|
||||
"""Вернуть {name: value} для литеральных top-level присваиваний файла."""
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
found = {}
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.Assign) or len(node.targets) != 1:
|
||||
continue
|
||||
target = node.targets[0]
|
||||
if isinstance(target, ast.Name) and target.id in names:
|
||||
found[target.id] = ast.literal_eval(node.value)
|
||||
return found
|
||||
|
||||
|
||||
def test_catalogue_is_structurally_consistent():
|
||||
assert cat.problems() == []
|
||||
|
||||
|
||||
def test_authorized_model_set_is_unchanged():
|
||||
assert cat.model_count() == 38
|
||||
assert len({m for r in cat.TIER_MODELS for m in cat.TIER_MODELS[r]}) == 38
|
||||
live = "deepseek-v4.1-flash-1017"
|
||||
dead = "deepseek-v4.1-flash"
|
||||
assert cat.TIER_MODELS[1].count(live) == 1
|
||||
assert live not in cat.TIER_MODELS[2] + cat.TIER_MODELS[3] + cat.TIER_MODELS[4]
|
||||
assert dead not in cat.CATALOGUE_MODELS
|
||||
assert cat.MODEL_DESCS[live]
|
||||
assert cat.min_rank(live) == 1
|
||||
assert cat.min_rank("kimi/kimi-k3.1-pro") == 3
|
||||
assert cat.min_rank("claude-opus-5.5") == 4
|
||||
|
||||
|
||||
def test_removed_dots_model_is_not_offered_or_resolved():
|
||||
removed = "dots-studio/dots-3-note-preview:free"
|
||||
assert removed not in cat.CATALOGUE_MODELS
|
||||
assert removed not in cat.MODEL_DESCS
|
||||
assert removed not in cat.ALIASES
|
||||
assert removed not in cat.ROUTING_ALIASES
|
||||
assert removed not in cat.ALIASES.values()
|
||||
assert removed not in cat.ROUTING_ALIASES.values()
|
||||
assert cat.min_rank(removed) is None
|
||||
for rank in cat.TIER_MODELS:
|
||||
assert removed not in cat.tier_models(rank)
|
||||
|
||||
|
||||
def test_every_catalogue_id_has_informative_metadata():
|
||||
for model in cat.CATALOGUE_MODELS:
|
||||
desc = cat.MODEL_DESCS[model]
|
||||
assert desc and desc != model
|
||||
assert len(cat.model_label(model)) >= 3
|
||||
assert cat.describe(model) == desc
|
||||
|
||||
|
||||
def test_min_rank_matches_first_tier_membership():
|
||||
for rank in cat.TIER_MODELS:
|
||||
for model in cat.TIER_MODELS[rank]:
|
||||
if model in cat.MIN_RANKS:
|
||||
assert cat.min_rank(model) <= rank
|
||||
assert set(cat.MIN_RANKS) == set(cat.CATALOGUE_MODELS)
|
||||
|
||||
|
||||
def test_aliases_are_metadata_only():
|
||||
for alias, model in cat.ALIASES.items():
|
||||
assert model in cat.CATALOGUE_MODELS
|
||||
assert alias not in cat.CATALOGUE_MODELS
|
||||
assert cat.canonical(alias) == model
|
||||
assert cat.min_rank(alias) == cat.min_rank(model)
|
||||
assert cat.MODEL_DESCS[alias] # подпись для кнопок/списков
|
||||
for alias in ("claude-opus-5-5", "claude-fable-5-1"):
|
||||
assert alias in cat.ALIASES
|
||||
assert alias in cat.MODEL_DESCS
|
||||
|
||||
|
||||
def test_routing_aliases_point_into_catalogue():
|
||||
for legacy, model in cat.ROUTING_ALIASES.items():
|
||||
assert model in cat.CATALOGUE_MODELS
|
||||
assert legacy not in cat.CATALOGUE_MODELS
|
||||
assert cat.ROUTING_ALIASES["deepseek-v4-flash"] == "deepseek-v4.1-flash-1017"
|
||||
|
||||
|
||||
def test_bot_literal_projection_matches_module():
|
||||
projection = _literal_assigns(BOT, {"TIER_MODELS", "MODEL_DESCS", "TIER_TITLES"})
|
||||
assert projection["TIER_MODELS"] == cat.TIER_MODELS
|
||||
assert projection["MODEL_DESCS"] == cat.MODEL_DESCS
|
||||
assert projection["TIER_TITLES"] == cat.TIER_TITLES
|
||||
|
||||
|
||||
def test_miniapp_literal_fallback_matches_module():
|
||||
literals = _literal_assigns(SERVER, {"TIER_MODELS", "MODEL_DESCS"})
|
||||
assert literals["TIER_MODELS"] == cat.TIER_MODELS
|
||||
assert literals["MODEL_DESCS"] == cat.MODEL_DESCS
|
||||
|
||||
|
||||
def test_catalogue_module_is_stdlib_only_and_carries_no_credentials():
|
||||
source = (ROOT / "bot" / "model_catalogue.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
for node in ast.walk(tree):
|
||||
assert not isinstance(node, (ast.Import, ast.ImportFrom)), "catalogue must not import anything"
|
||||
lowered = source.lower()
|
||||
for marker in ("http://", "https://", "api_key", "apikey", "bearer", "password", "secret"):
|
||||
assert marker not in lowered
|
||||
for model in cat.TIER_MODELS[1]:
|
||||
assert isinstance(model, str) and model # только идентификаторы, без порогов доступности
|
||||
|
||||
|
||||
def test_public_aliases_do_not_expand_the_offered_set():
|
||||
"""Алиас не должен появляться в тир-списках: доступ выдаётся по рангу канонической модели."""
|
||||
for alias in cat.ALIASES:
|
||||
assert all(alias not in models for models in cat.TIER_MODELS.values())
|
||||
|
||||
|
||||
def test_model_descriptions_are_unique_per_family_marker():
|
||||
labels = [cat.model_label(model) for model in cat.CATALOGUE_MODELS]
|
||||
assert len(set(labels)) == len(labels), "две модели делят одну подпись кнопки"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(pytest.main([__file__, "-q"]))
|
||||
@@ -0,0 +1,61 @@
|
||||
import unittest
|
||||
|
||||
from model_identity import canonical_model, ModelIdentityError, check_response_model, same_original_model
|
||||
|
||||
|
||||
class ModelIdentityTests(unittest.TestCase):
|
||||
def test_normalization_preserves_literal_separators_and_unicode_versions(self):
|
||||
cases = (
|
||||
(" ANTHROPIC/CLAUDE_5.5_OPUS ", "anthropic/claude-5-5-opus"),
|
||||
(" ANTHROPIC/CLAUDE-5.5_OPUS ", "claude-opus-5-5"),
|
||||
("opus_5.5", "claude-opus-5-5"),
|
||||
("claude_٥.٥_sonnet", "claude-sonnet-٥-٥"),
|
||||
("unknown/claude_5.5_opus", "unknown/claude-5-5-opus"),
|
||||
("gpt_6.1_sol-uncensored", "gpt-6-1-sol"),
|
||||
("model...___name", "model------name"),
|
||||
("claude-5-5-opus\nextra", "claude-5-5-opus\nextra"),
|
||||
)
|
||||
for name, expected in cases:
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(canonical_model(name), expected)
|
||||
|
||||
def test_non_string_and_empty_model_names_remain_absent(self):
|
||||
for name in (None, 0, False, [], {}, "", " \t\n"):
|
||||
with self.subTest(name=name):
|
||||
self.assertEqual(canonical_model(name), "")
|
||||
|
||||
def test_spelling_and_documented_creator_aliases_are_equivalent(self):
|
||||
self.assertTrue(same_original_model('anthropic/claude-opus-5.5', 'claude-5-5-opus'))
|
||||
self.assertTrue(same_original_model('deepseek-ai/DeepSeek-v4.1-Flash', 'deepseek-v4-1-flash'))
|
||||
|
||||
def test_distinct_explicit_snapshots_are_never_collapsed(self):
|
||||
self.assertFalse(same_original_model('deepseek-v4-flash-0731', 'deepseek-v4-flash-0801'))
|
||||
self.assertFalse(same_original_model('deepseek-v4-flash-0731', 'deepseek-v4-flash'))
|
||||
self.assertTrue(same_original_model('deepseek-v4-flash-0731', 'deepseek-v4-flash-0731'))
|
||||
|
||||
def test_live_flash_route_requires_the_exact_snapshot_identity(self):
|
||||
exact = "deepseek-v4.1-flash-1017"
|
||||
self.assertTrue(same_original_model(exact, exact))
|
||||
self.assertFalse(same_original_model(exact, "deepseek-v4.1-flash"))
|
||||
check_response_model(exact, {"model": exact})
|
||||
with self.assertRaises(ModelIdentityError):
|
||||
check_response_model(exact, {"model": "deepseek-v4.1-flash"})
|
||||
|
||||
def test_provider_cannot_replace_family_or_strip_unknown_creator(self):
|
||||
for requested, actual in (('claude-opus-5-5', 'claude-sonnet-5-5'),
|
||||
('gpt-6-1-sol', 'codai'),
|
||||
('counterfeit/claude-opus-5-5', 'claude-opus-5-5')):
|
||||
with self.subTest(requested=requested, actual=actual):
|
||||
with self.assertRaises(ModelIdentityError):
|
||||
check_response_model(requested, {'model': actual})
|
||||
|
||||
def test_optional_absent_identity_is_not_fabricated_or_a_success_attestation(self):
|
||||
payload = {'choices': [{'message': {'content': 'I am the original vendor model'}}]}
|
||||
before = repr(payload)
|
||||
check_response_model('exact-model', payload)
|
||||
self.assertEqual(repr(payload), before)
|
||||
self.assertNotIn('model', payload)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Vendor-reference model metadata contract (static JSON + loader).
|
||||
|
||||
Reference numbers must be honest: exact-id matches only, unknown models explicitly
|
||||
unknown, no inference of an input limit from the context window, and a broken or
|
||||
missing reference file degrades to "no reference" instead of failing the catalogue.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import model_metadata
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
SPECS = os.path.join(os.path.dirname(HERE), "bot", "model_specs.json")
|
||||
SOURCE = "https://openrouter.ai/api/v1/models"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _canonical_specs(monkeypatch):
|
||||
monkeypatch.delenv("IISHKO_MODEL_SPECS", raising=False)
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
yield
|
||||
monkeypatch.delenv("IISHKO_MODEL_SPECS", raising=False)
|
||||
model_metadata.reload()
|
||||
|
||||
|
||||
def test_reference_file_is_shipped_and_scoped():
|
||||
document = json.load(open(SPECS, encoding="utf-8"))
|
||||
assert document["scope"] == "vendor_reference"
|
||||
assert document["gateway_verified"] is False
|
||||
assert document["source"] == SOURCE
|
||||
assert document["models"], "reference must list the ids it actually maps"
|
||||
for entry in document["models"].values():
|
||||
assert entry["max_input_tokens"] is None
|
||||
|
||||
|
||||
def test_exact_id_reference_values():
|
||||
meta = model_metadata.for_model("deepseek-v4.1-flash-1017")
|
||||
assert meta["known"] is True
|
||||
assert meta["scope"] == "vendor_reference"
|
||||
assert meta["source_model"] == "deepseek/deepseek-v4.1-flash-1017"
|
||||
assert meta["context_window"] == 1048576
|
||||
assert meta["max_output_tokens"] == 393216
|
||||
assert meta["gateway_verified"] is False
|
||||
|
||||
|
||||
def test_input_limit_is_never_inferred_from_context_window():
|
||||
meta = model_metadata.for_model("grok-4.6")
|
||||
assert meta["context_window"] == 500000
|
||||
assert meta["max_output_tokens"] == 450000
|
||||
assert meta["max_input_tokens"] is None
|
||||
|
||||
|
||||
def test_entity_qualified_alias_is_the_only_mapped_variant():
|
||||
mapped = model_metadata.for_model("kimi/kimi-k3.1-pro")
|
||||
assert mapped["known"] is True
|
||||
assert mapped["source_model"] == "moonshotai/kimi-k3.1-pro"
|
||||
# A narrower/suffixed variant must not inherit the plain model's numbers.
|
||||
for unknown_id in ("kimi/kimi-k3.1-pro-highspeed", "kimi-k3.1-pro", "qwen3.8-max",
|
||||
"qwen-plus", "qwen-max", "gpt-6-luna", "claude-opus-5-5",
|
||||
"gemini-auto", "totally-made-up"):
|
||||
meta = model_metadata.for_model(unknown_id)
|
||||
assert meta["model"] == unknown_id
|
||||
assert meta["known"] is False
|
||||
assert meta["scope"] == "unknown"
|
||||
assert meta["context_window"] is None
|
||||
assert meta["max_output_tokens"] is None
|
||||
assert meta["max_input_tokens"] is None
|
||||
assert meta["source_model"] is None
|
||||
assert meta["gateway_verified"] is False
|
||||
|
||||
|
||||
def test_bot_output_budget_is_not_a_vendor_limit():
|
||||
describe = model_metadata.describe()
|
||||
budget = describe["bot_output_budget"]
|
||||
assert budget["not_a_vendor_limit"] is True
|
||||
assert budget["scope"] == "bot_runtime_local"
|
||||
assert (budget["normal"], budget["max"]) == (8000, 16000)
|
||||
vendor = model_metadata.for_model("deepseek-v4.1-flash")
|
||||
assert vendor["max_output_tokens"] != budget["normal"]
|
||||
|
||||
|
||||
def test_unknown_shape_is_complete_and_null():
|
||||
meta = model_metadata.for_model("nope")
|
||||
assert set(meta) == {"model", "known", "scope", "source", "source_model",
|
||||
"context_window", "max_input_tokens", "max_output_tokens",
|
||||
"gateway_verified"}
|
||||
|
||||
|
||||
def test_returned_metadata_is_a_copy():
|
||||
first = model_metadata.for_model("glm-5.3")
|
||||
first["context_window"] = 1
|
||||
first["highest"] = "mutated"
|
||||
second = model_metadata.for_model("glm-5.3")
|
||||
assert second["context_window"] == 1048576
|
||||
assert "highest" not in second
|
||||
assert SOURCE == second["source"]
|
||||
|
||||
|
||||
def test_attach_rows_is_additive_and_preserves_input():
|
||||
rows = [{"id": "grok-4.7", "object": "model", "owned_by": "x-ai", "extra": [1, 2]},
|
||||
{"id": "unknown-model", "object": "model"},
|
||||
{"object": "model"},
|
||||
"not-a-dict"]
|
||||
enriched = model_metadata.attach_rows(rows)
|
||||
assert len(enriched) == len(rows)
|
||||
assert enriched[0]["id"] == "grok-4.7"
|
||||
assert enriched[0]["object"] == "model"
|
||||
assert enriched[0]["owned_by"] == "x-ai"
|
||||
assert enriched[0]["extra"] == [1, 2]
|
||||
assert enriched[0]["model_metadata"]["max_output_tokens"] == 450000
|
||||
assert enriched[1]["model_metadata"]["known"] is False
|
||||
assert "model_metadata" not in rows[0] # source rows untouched
|
||||
assert "model_metadata" not in enriched[2] # no id -> no claim
|
||||
assert enriched[3] == "not-a-dict"
|
||||
|
||||
|
||||
def test_for_models_covers_every_requested_id():
|
||||
result = model_metadata.for_models(["glm-5.3", "unknown-model"])
|
||||
assert set(result) == {"glm-5.3", "unknown-model"}
|
||||
assert result["glm-5.3"]["known"] is True
|
||||
assert result["unknown-model"]["known"] is False
|
||||
|
||||
|
||||
def test_missing_file_fails_safe(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", str(tmp_path / "absent.json"))
|
||||
model_metadata.reload()
|
||||
assert model_metadata.available() is False
|
||||
rows = [{"id": "grok-4.7", "object": "model"}]
|
||||
enriched = model_metadata.attach_rows(rows)
|
||||
assert enriched == rows
|
||||
assert enriched is not rows or "model_metadata" not in enriched[0]
|
||||
assert model_metadata.for_model("grok-4.7")["known"] is False
|
||||
assert model_metadata.describe()["scope"] == "unknown"
|
||||
|
||||
|
||||
def test_empty_override_disables_reference(monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", "")
|
||||
model_metadata.reload()
|
||||
assert model_metadata.available() is False
|
||||
assert model_metadata.describe()["known_models"] == 0
|
||||
|
||||
|
||||
def test_malformed_file_fails_safe(tmp_path, monkeypatch):
|
||||
path = tmp_path / "broken.json"
|
||||
path.write_text('{"models": {"grok-4.7": {"context_window": "a lot"}}', encoding="utf-8")
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", str(path))
|
||||
model_metadata.reload()
|
||||
assert model_metadata.for_model("grok-4.7")["known"] is False
|
||||
path.write_text('{"models": {"grok-4.7": {"context_window": "a lot", '
|
||||
'"max_output_tokens": -1, "source_model": "x-ai/grok-4.7"}}}',
|
||||
encoding="utf-8")
|
||||
model_metadata.reload()
|
||||
meta = model_metadata.for_model("grok-4.7")
|
||||
assert meta["context_window"] is None
|
||||
assert meta["max_output_tokens"] is None
|
||||
assert meta["max_input_tokens"] is None
|
||||
|
||||
|
||||
def test_oversized_file_is_ignored(tmp_path, monkeypatch):
|
||||
path = tmp_path / "big.json"
|
||||
path.write_text('{"models": {}}' + " " * (model_metadata.MAX_BYTES + 16), encoding="utf-8")
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", str(path))
|
||||
model_metadata.reload()
|
||||
assert model_metadata.available() is False
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Transport regressions: GET /v1/models metadata on the transparent (is_api) path.
|
||||
|
||||
The production skin proxies every ``/v1/`` call through the transparent branch, so the
|
||||
catalogue hook must run there too. Each case drives the skin's real helper plus the real
|
||||
``relay_api`` over a real aiohttp upstream and a real HTTP client: one upstream request,
|
||||
enriched 200 JSON, byte-exact fallbacks, no replay on errors and no corrupted gzip.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from multidict import CIMultiDict
|
||||
from yarl import URL
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
ROOT = os.path.dirname(HERE)
|
||||
CANON_SKIN = os.path.join(ROOT, "gateway", "grok-web-skin.py")
|
||||
CANDIDATE_SKIN = os.environ.get("IISHKO_CANDIDATE_SKIN")
|
||||
SPECS = os.path.join(ROOT, "bot", "model_specs.json")
|
||||
|
||||
sys.path.insert(0, os.path.join(ROOT, "gateway"))
|
||||
import model_metadata
|
||||
from gateway_errors import HOP_HEADERS
|
||||
from transparent_api import relay_api
|
||||
|
||||
SKINS = [CANON_SKIN] + ([CANDIDATE_SKIN] if CANDIDATE_SKIN else [])
|
||||
SKINS = [path for path in SKINS if os.path.exists(path)]
|
||||
SKIN_IDS = ["canonical", "candidate"][:len(SKINS)]
|
||||
HELPERS = ("_attach_model_metadata", "_models_catalogue_response", "response_headers")
|
||||
|
||||
CATALOGUE = {"object": "list", "data": [
|
||||
{"id": "grok-4.6", "object": "model", "owned_by": "x-ai"},
|
||||
{"id": "totally-unknown-model", "object": "model", "owned_by": "vendor-x"},
|
||||
{"id": "glm-5.3", "object": "model", "owned_by": "z-ai", "tags": ["chat"]},
|
||||
]}
|
||||
|
||||
|
||||
def _parsed(path):
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
source = handle.read()
|
||||
return source, ast.parse(source)
|
||||
|
||||
|
||||
def _skin(path):
|
||||
"""Exec the real helpers of a skin plus the transparent-path dispatch shim."""
|
||||
_source, tree = _parsed(path)
|
||||
funcs = {node.name: node for node in tree.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||
ns = {
|
||||
"asyncio": asyncio, "json": json, "os": os, "aiohttp": aiohttp, "web": web,
|
||||
"URL": URL, "CIMultiDict": CIMultiDict, "HOP_HEADERS": HOP_HEADERS,
|
||||
"LOG": logging.getLogger("models-transport"), "model_metadata": model_metadata,
|
||||
"relay_api": relay_api, "UPSTREAM": "http://127.0.0.1:1",
|
||||
"_key_balance_usd": lambda key: 7.5,
|
||||
}
|
||||
for name in HELPERS:
|
||||
node = funcs[name]
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), path, "exec"), ns)
|
||||
return ns
|
||||
|
||||
|
||||
class _Skin:
|
||||
"""Full transparent dispatch of one skin: hook first, relay_api on the same upstream."""
|
||||
|
||||
def __init__(self, ns, upstream):
|
||||
self.ns = ns
|
||||
self.upstream = upstream.rstrip("/")
|
||||
self.ns["UPSTREAM"] = self.upstream
|
||||
|
||||
async def __call__(self, request):
|
||||
req = request
|
||||
headers = dict(req.headers)
|
||||
async with aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=30)) as session:
|
||||
if self.ns["_models_catalogue_response"].__code__.co_kwonlyargcount:
|
||||
# candidate shape: the helper owns the single session.request.
|
||||
return await self.ns["_models_catalogue_response"](
|
||||
req, session, headers=headers, body=b"",
|
||||
balance_lookup=self.ns["_key_balance_usd"])
|
||||
async with session.request("GET", URL(self.upstream + req.raw_path),
|
||||
headers=headers, auto_decompress=False,
|
||||
skip_auto_headers={"Accept-Encoding"}) as upstream:
|
||||
if req.method == "GET" and req.path == "/v1/models":
|
||||
response = await self.ns["_models_catalogue_response"](req, upstream)
|
||||
if response is not None:
|
||||
return response
|
||||
return await self.ns["relay_api"](req, upstream)
|
||||
|
||||
|
||||
class _Upstream:
|
||||
def __init__(self, status=200, body=b"{}", headers=None):
|
||||
self.status, self.body = status, body
|
||||
self.headers = headers or {}
|
||||
self.hits = 0
|
||||
|
||||
async def __call__(self, request):
|
||||
self.hits += 1
|
||||
return web.Response(status=self.status, body=self.body, headers=self.headers)
|
||||
|
||||
|
||||
async def _exercise(ns, script):
|
||||
"""Serve one scripted upstream and the skin dispatch over real HTTP; return (client, hits)."""
|
||||
upstream = _Upstream(*script)
|
||||
upstream_app = web.Application()
|
||||
upstream_app["seen"] = upstream
|
||||
upstream_app.router.add_route("*", "/{tail:.*}", upstream)
|
||||
runner = web.AppRunner(upstream_app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
skin = _Skin(ns, "http://127.0.0.1:%d" % port)
|
||||
gateway = web.Application()
|
||||
async def handler(request):
|
||||
return await skin(request)
|
||||
gateway.router.add_route("*", "/{tail:.*}", handler)
|
||||
gateway_runner = web.AppRunner(gateway)
|
||||
await gateway_runner.setup()
|
||||
gateway_site = web.TCPSite(gateway_runner, "127.0.0.1", 0)
|
||||
await gateway_site.start()
|
||||
gateway_port = gateway_site._server.sockets[0].getsockname()[1]
|
||||
session = aiohttp.ClientSession()
|
||||
response = await session.get("http://127.0.0.1:%d/v1/models" % gateway_port,
|
||||
headers={"Authorization": "Bearer test-key"})
|
||||
body = await response.read()
|
||||
result = (response.status, dict(response.headers), body, upstream.hits)
|
||||
await response.release()
|
||||
await session.close()
|
||||
for closing in (gateway_runner, runner):
|
||||
await closing.cleanup()
|
||||
return result
|
||||
|
||||
|
||||
def _run(skin_path, script):
|
||||
pytest.importorskip("aiohttp")
|
||||
ns = _skin(skin_path)
|
||||
return asyncio.run(_exercise(ns, script))
|
||||
|
||||
|
||||
def _json_script(payload, headers=None, status=200):
|
||||
body = json.dumps(payload).encode()
|
||||
return (status, body, dict({"Content-Type": "application/json"}, **(headers or {})))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_models_get_carries_metadata_in_one_upstream_request(skin, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
status, _headers, body, hits = _run(skin, _json_script(CATALOGUE))
|
||||
assert status == 200 and hits == 1
|
||||
payload = json.loads(body)
|
||||
assert [row["id"] for row in payload["data"]] == [row["id"] for row in CATALOGUE["data"]]
|
||||
assert payload["object"] == "list"
|
||||
known, unknown, other = payload["data"]
|
||||
assert known["owned_by"] == "x-ai" and other["tags"] == ["chat"]
|
||||
assert known["model_metadata"]["context_window"] == 500000
|
||||
assert known["model_metadata"]["gateway_verified"] is False
|
||||
assert unknown["model_metadata"]["known"] is False
|
||||
assert unknown["model_metadata"]["context_window"] is None
|
||||
assert other["model_metadata"]["known"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
@pytest.mark.parametrize("validator_names", [
|
||||
("ETag", "Content-MD5"), ("etag", "content-md5"), ("Etag", "Content-Md5"),
|
||||
])
|
||||
def test_models_get_drops_stale_validators(skin, monkeypatch, validator_names):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
headers = dict(zip(validator_names, ('"stale"', "c29tZS1kaWdlc3Q=")))
|
||||
status, response_headers, body, hits = _run(skin, _json_script(CATALOGUE, headers))
|
||||
assert status == 200 and hits == 1
|
||||
assert "model_metadata" in json.loads(body)["data"][0]
|
||||
lowered = {key.lower() for key in response_headers}
|
||||
assert "etag" not in lowered and "content-md5" not in lowered
|
||||
assert int(response_headers["Content-Length"]) == len(body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_models_get_without_reference_is_byte_exact(skin, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", "")
|
||||
model_metadata.reload()
|
||||
raw = b'{"data": [ {"id": "grok-4.6"} ] }'
|
||||
status, _headers, body, hits = _run(skin, (200, raw, {"Content-Type": "application/json"}))
|
||||
assert status == 200 and hits == 1
|
||||
assert body == raw
|
||||
assert "model_metadata" not in body.decode()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_models_get_unparseable_body_is_byte_exact(skin, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
raw = b'{"data": ['
|
||||
status, _headers, body, hits = _run(skin, (200, raw, {"Content-Type": "application/json"}))
|
||||
assert status == 200 and hits == 1
|
||||
assert body == raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_models_get_gzip_reply_is_not_corrupted(skin, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
packed = gzip.compress(json.dumps(CATALOGUE).encode())
|
||||
status, headers, body, hits = _run(
|
||||
skin, (200, packed, {"Content-Type": "application/json", "Content-Encoding": "gzip"}))
|
||||
assert status == 200 and hits == 1
|
||||
assert headers["Content-Type"].startswith("application/json")
|
||||
assert [row["id"] for row in json.loads(body)["data"]] == [row["id"] for row in CATALOGUE["data"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_models_error_is_normalized_without_replay(skin, monkeypatch):
|
||||
monkeypatch.setenv("IISHKO_MODEL_SPECS", SPECS)
|
||||
model_metadata.reload()
|
||||
payload = {"error": {"message": "slow down", "type": "rate_limit_error"}}
|
||||
status, headers, body, hits = _run(skin, _json_script(payload, status=429))
|
||||
assert hits == 1
|
||||
assert status == 429 # Explicit upstream busy remains retryable without inventing a 503.
|
||||
assert headers["Content-Type"].startswith("application/json")
|
||||
assert json.loads(body)["error"]["code"] == "upstream_busy"
|
||||
assert json.loads(body)["error"]["retryable"] is True
|
||||
assert "model_metadata" not in body.decode()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=SKIN_IDS)
|
||||
def test_hook_is_wired_after_gates_before_transparent_dispatch(skin):
|
||||
_source, tree = _parsed(skin)
|
||||
proxy = next(node for node in tree.body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "proxy")
|
||||
calls = [node for node in ast.walk(proxy) if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name) and node.func.id == "_models_catalogue_response"]
|
||||
assert len(calls) == 1, "single hook call inside the handler"
|
||||
hook = calls[0]
|
||||
guard = [node for node in ast.walk(proxy) if isinstance(node, ast.If)
|
||||
and "/v1/models" in ast.dump(node.test) and "GET" in ast.dump(node.test)]
|
||||
assert guard and guard[0].lineno < hook.lineno < guard[0].end_lineno
|
||||
dispatch = [node.lineno for node in ast.walk(proxy) if isinstance(node, ast.Call)
|
||||
and isinstance(node.func, ast.Name)
|
||||
and node.func.id in ("relay_api", "relay_api_request")]
|
||||
assert [line for line in dispatch if line > hook.lineno], "dispatch stays after the hook"
|
||||
for gate in ("gate_check", "_rl_check_sync"):
|
||||
located = [node.lineno for node in ast.walk(proxy) if isinstance(node, ast.Call)
|
||||
and ((isinstance(node.func, ast.Name) and node.func.id == gate)
|
||||
or (isinstance(node.func, ast.Attribute) and node.func.attr == "to_thread"
|
||||
and node.args and isinstance(node.args[0], ast.Name)
|
||||
and node.args[0].id == gate))]
|
||||
assert located and max(located) < hook.lineno, "gate %s runs before the hook" % gate
|
||||
@@ -0,0 +1,146 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const html = readFileSync(process.env.IISHKO_UI_HTML || new URL('../bot/webapp/static/index.html', import.meta.url), 'utf8');
|
||||
const lines = html.split(/\r?\n/);
|
||||
function declaration(prefix) {
|
||||
const line = lines.find(value => value.startsWith(prefix));
|
||||
assert.ok(line, `Missing application declaration: ${prefix}`);
|
||||
return line;
|
||||
}
|
||||
function between(start, end) {
|
||||
const first = html.indexOf(start);
|
||||
const last = html.indexOf(end, first + start.length);
|
||||
assert.ok(first >= 0 && last > first, `Missing source block: ${start}`);
|
||||
return html.slice(first, last);
|
||||
}
|
||||
const source = [
|
||||
...['const esc=', 'const num=', 'const fmt=', 'const STATUS_UI='].map(declaration),
|
||||
between('function publicConnectionField(', 'function connectionHelpHtml('),
|
||||
between('function modelStatus(', 'const STATUS_UI='),
|
||||
between('function modelAgentEligible(', 'function modelsEmptyHtml('),
|
||||
between('function uptimeHtml(', 'function modelsFiltered('),
|
||||
].join('\n');
|
||||
const advisory = {
|
||||
label: 'Строгая модерация провайдера',
|
||||
notice: 'На части маршрутов действует контент-фильтр провайдера. Отказ не означает недоступность модели; повтор того же текста может не помочь.',
|
||||
};
|
||||
const badgePattern = /<span class="tag moderation-advisory" role="note" title="[^"]*" aria-label="[^"]*">[^<]*<\/span>/g;
|
||||
const badgeAbsent = /<span class="tag moderation-advisory"/;
|
||||
const model = overrides => ({
|
||||
name: 'vendor/exact-model:v1', display_name: 'Название модели', available: true,
|
||||
min_rank: 2, rank_name: 'Участник', status: 'up', checked_at: Date.now() / 1000,
|
||||
ms: 42, p_in: 0.1, p_out: 0.2, desc: 'Описание модели', ...overrides,
|
||||
});
|
||||
function harness(row) {
|
||||
const selected = [], routes = [];
|
||||
const context = vm.createContext({
|
||||
row, mList: [row], mMeta: {status_ts: 0, status_stale_after: 120}, AG_LABEL: {},
|
||||
agentModelsLoaded: true, agentModels: [row.name], agentBusy: false,
|
||||
agentOperations: {current: () => null}, resolvedUid: '123', current: 'models',
|
||||
ago: () => 'только что', $: () => null,
|
||||
selectAgentModel: id => { selected.push(id); return true; },
|
||||
goRoute: route => routes.push(route),
|
||||
loadAgentModels: async () => { throw new Error('Loaded model selection must not reload'); },
|
||||
button: {disabled: false, isConnected: true},
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
return {
|
||||
context, selected, routes,
|
||||
run: expression => vm.runInContext(expression, context),
|
||||
render: (chatModel = '') => { context.chatModel = chatModel; return vm.runInContext('modelCard(row, chatModel)', context); },
|
||||
};
|
||||
}
|
||||
|
||||
test('actual modelCard renders advisory as visible tag text with the notice in title', () => {
|
||||
const row = model({provider_moderation: advisory});
|
||||
const before = JSON.stringify(row);
|
||||
const view = harness(row).render();
|
||||
assert.ok(view.includes(`<span class="tag moderation-advisory" role="note" title="${advisory.notice}" aria-label="${advisory.label}. ${advisory.notice}">${advisory.label}</span>`));
|
||||
assert.equal(view.match(badgePattern)?.length, 1);
|
||||
assert.equal(JSON.stringify(row), before, 'rendering must not mutate model metadata');
|
||||
assert.ok(view.indexOf('model-name') < view.indexOf('moderation-advisory'));
|
||||
assert.ok(view.indexOf('moderation-advisory') < view.indexOf('ID модели'));
|
||||
});
|
||||
|
||||
test('missing, null, non-object and incomplete advisory values produce no badge', () => {
|
||||
assert.doesNotMatch(harness(model()).render(), badgeAbsent);
|
||||
const invalid = [
|
||||
undefined, null, false, 1, 'strict', [], {},
|
||||
{label: advisory.label}, {notice: advisory.notice},
|
||||
{label: '', notice: advisory.notice}, {label: ' \n\t', notice: advisory.notice},
|
||||
{label: advisory.label, notice: ''}, {label: advisory.label, notice: ' \n\t'},
|
||||
{label: 42, notice: advisory.notice}, {label: advisory.label, notice: 42},
|
||||
{label: {}, notice: advisory.notice}, {label: advisory.label, notice: {}},
|
||||
Object.assign([], advisory),
|
||||
];
|
||||
for (const value of invalid) {
|
||||
assert.doesNotMatch(harness(model({provider_moderation: value})).render(), badgeAbsent, JSON.stringify(value));
|
||||
}
|
||||
});
|
||||
|
||||
test('actual existing esc utility escapes malicious label text and title attribute independently', () => {
|
||||
const label = '<img src=x onerror="alert(1)"> & \'label\'';
|
||||
const notice = '"><svg onload=\'alert(2)\'> & "notice"';
|
||||
const view = harness(model({provider_moderation: {label, notice}})).render();
|
||||
const escapedLabel = '<img src=x onerror="alert(1)"> & 'label'';
|
||||
const escapedNotice = '"><svg onload='alert(2)'> & "notice"';
|
||||
assert.ok(view.includes(`<span class="tag moderation-advisory" role="note" title="${escapedNotice}" aria-label="${escapedLabel}. ${escapedNotice}">${escapedLabel}</span>`));
|
||||
assert.equal(view.match(badgePattern)?.length, 1);
|
||||
assert.doesNotMatch(view, /<img\b|<svg\b|"\s+onload=|"\s+onerror=/);
|
||||
assert.ok(!view.includes(label));
|
||||
assert.ok(!view.includes(notice));
|
||||
});
|
||||
|
||||
test('advisory is additive only: display, identity, ACL, rank, health and actions stay identical', () => {
|
||||
for (const status of ['up', 'busy', 'down', 'stale']) {
|
||||
for (const available of [true, false]) {
|
||||
for (const selected of [true, false]) {
|
||||
const row = model({status, available, name: 'vendor/exact<id>&"\':v1'});
|
||||
const chatModel = selected ? row.name : 'another-model';
|
||||
const baseline = harness(row).render(chatModel);
|
||||
const marked = harness({...row, provider_moderation: advisory}).render(chatModel);
|
||||
assert.equal(marked.replace(badgePattern, ''), baseline);
|
||||
assert.match(marked, /value="vendor\/exact<id>&"':v1"/);
|
||||
// Canonical UI has the provider action; the production fork may not.
|
||||
// Never add an unrelated action during an advisory-only production rebase.
|
||||
if (!process.env.IISHKO_UI_HTML || baseline.includes('data-provider-model=')) {
|
||||
assert.match(marked, /data-provider-model="vendor\/exact<id>&"':v1"/);
|
||||
}
|
||||
assert.equal(marked.includes('В чате бота'), selected);
|
||||
assert.equal(marked.includes('data-open-agent='), available);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('actual selection handler preserves the exact model ID and route with or without advisory', async () => {
|
||||
for (const provider_moderation of [undefined, advisory]) {
|
||||
const row = model({provider_moderation});
|
||||
const h = harness(row);
|
||||
assert.ok(h.render().includes(`data-open-agent="${row.name}"`));
|
||||
assert.equal(await h.run('openModelInAgent(row.name, button)'), true);
|
||||
assert.deepEqual(h.selected, [row.name]);
|
||||
assert.deepEqual(h.routes, ['agent']);
|
||||
assert.equal(h.context.button.disabled, false);
|
||||
}
|
||||
assert.ok(html.includes("const agentOpen=event.target.closest('[data-open-agent]');"));
|
||||
assert.ok(html.includes('openModelInAgent(agentOpen.dataset.openAgent,agentOpen)'));
|
||||
});
|
||||
|
||||
test('advisory never enables an unavailable model or bypasses an active agent operation', async () => {
|
||||
for (const provider_moderation of [undefined, advisory]) {
|
||||
const locked = harness(model({available: false, provider_moderation}));
|
||||
assert.doesNotMatch(locked.render(), /data-open-agent=/);
|
||||
assert.equal(await locked.run('openModelInAgent(row.name, button)'), false);
|
||||
assert.deepEqual(locked.selected, []);
|
||||
assert.deepEqual(locked.routes, []);
|
||||
const busy = harness(model({provider_moderation}));
|
||||
busy.context.agentBusy = true;
|
||||
assert.equal(await busy.run('openModelInAgent(row.name, button)'), false);
|
||||
assert.deepEqual(busy.selected, []);
|
||||
assert.deepEqual(busy.routes, []);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,508 @@
|
||||
"""Behavioural tests for bot/moderation_bridge.py using aiogram-shaped fakes.
|
||||
|
||||
Fakes mirror real aiogram objects: supergroup ids are negative and
|
||||
``ChatMemberRestricted`` exposes flat ``can_*`` flags plus ``datetime``
|
||||
``until_date`` (there is no ``.permissions`` on it).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "bot"))
|
||||
|
||||
from aiogram import Router
|
||||
|
||||
import account_admin
|
||||
import moderation_bridge as mb
|
||||
|
||||
NOW = 1_700_000_000
|
||||
CHAT_ID = -1001234567890
|
||||
GROUP = SimpleNamespace(id=CHAT_ID, type="supergroup", title="Test")
|
||||
BOT_ID = 999
|
||||
ADMIN_ID = 7
|
||||
TARGET_ID = 42
|
||||
|
||||
|
||||
class FakeUser:
|
||||
def __init__(self, uid, username="", first_name="User", is_bot=False):
|
||||
self.id = uid
|
||||
self.username = username
|
||||
self.first_name = first_name
|
||||
self.last_name = None
|
||||
self.is_bot = is_bot
|
||||
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self, chat_id=CHAT_ID, chat_type="supergroup"):
|
||||
self.id = chat_id
|
||||
self.type = chat_type
|
||||
self.title = "Test"
|
||||
|
||||
|
||||
class FakeMessage:
|
||||
def __init__(self, text="", user=None, chat=None, reply_to_message=None, new_chat_members=None):
|
||||
self.text = text
|
||||
self.from_user = user or FakeUser(ADMIN_ID, "admin")
|
||||
self.chat = chat or FakeChat()
|
||||
self.reply_to_message = reply_to_message
|
||||
self.new_chat_members = new_chat_members
|
||||
|
||||
|
||||
def _perms(**overrides):
|
||||
values = {field: True for field in mb.PERMISSION_FIELDS}
|
||||
values.update(overrides)
|
||||
return SimpleNamespace(**values)
|
||||
|
||||
|
||||
class FlatRestricted:
|
||||
"""Shape of aiogram ChatMemberRestricted: flat flags, datetime until_date."""
|
||||
|
||||
status = "restricted"
|
||||
|
||||
def __init__(self, until_date=0, user=None, **overrides):
|
||||
self.until_date = until_date
|
||||
self.user = user or FakeUser(TARGET_ID)
|
||||
for field in mb.PERMISSION_FIELDS:
|
||||
setattr(self, field, overrides.get(field, False))
|
||||
|
||||
|
||||
class Member:
|
||||
"""ChatMember shape: permissions and admin rights are both flat fields."""
|
||||
|
||||
ADMIN_RIGHTS = (
|
||||
"can_restrict_members",
|
||||
"can_delete_messages",
|
||||
"can_promote_members",
|
||||
"can_change_info",
|
||||
"can_invite_users",
|
||||
"can_pin_messages",
|
||||
"can_manage_chat",
|
||||
"can_manage_video_chats",
|
||||
)
|
||||
|
||||
def __init__(self, status="member", user=None, **flags):
|
||||
self.status = status
|
||||
self.user = user or FakeUser(TARGET_ID)
|
||||
for field in mb.PERMISSION_FIELDS + self.ADMIN_RIGHTS:
|
||||
setattr(self, field, flags.get(field, False))
|
||||
|
||||
|
||||
class FakeBot:
|
||||
def __init__(self, members=None, chat_permissions=None):
|
||||
self.members = dict(members or {})
|
||||
self.chat_permissions = chat_permissions or _perms()
|
||||
self.sent = []
|
||||
self.restricted = []
|
||||
self.banned = []
|
||||
self.unbanned = []
|
||||
self.member_calls = []
|
||||
self.chat_calls = []
|
||||
self.chat_error = None
|
||||
self.me = FakeUser(BOT_ID, "iishko_bot", is_bot=True)
|
||||
|
||||
async def get_me(self):
|
||||
return self.me
|
||||
|
||||
def set_member(self, chat_id, uid, member):
|
||||
"""Inject an externally changed member state (e.g. a manual restriction)."""
|
||||
self.members[(int(chat_id), int(uid))] = member
|
||||
|
||||
async def get_chat_member(self, chat_id, uid):
|
||||
self.member_calls.append((int(chat_id), int(uid)))
|
||||
value = self.members.get((int(chat_id), int(uid)))
|
||||
if isinstance(value, Exception):
|
||||
raise value
|
||||
if value is None:
|
||||
raise RuntimeError("Bad Request: user not found")
|
||||
return value
|
||||
|
||||
async def get_chat(self, chat_id):
|
||||
self.chat_calls.append(int(chat_id))
|
||||
if self.chat_error is not None:
|
||||
raise self.chat_error
|
||||
return SimpleNamespace(id=int(chat_id), type="supergroup", permissions=self.chat_permissions)
|
||||
|
||||
async def send_message(self, **kwargs):
|
||||
self.sent.append(kwargs)
|
||||
return SimpleNamespace(message_id=len(self.sent))
|
||||
|
||||
async def restrict_chat_member(self, chat_id, uid, permissions=None, until_date=0):
|
||||
chat_id = int(chat_id)
|
||||
uid = int(uid)
|
||||
self.restricted.append((chat_id, uid, permissions, until_date))
|
||||
bits = {
|
||||
field: bool(getattr(permissions, field, False))
|
||||
for field in mb.PERMISSION_FIELDS
|
||||
}
|
||||
current = self.members.get((chat_id, uid))
|
||||
user = getattr(current, "user", None) or FakeUser(uid)
|
||||
if all(bits.values()) and not until_date:
|
||||
# Telegram returns a plain ChatMember after a fully open restriction.
|
||||
self.members[(chat_id, uid)] = Member("member", user)
|
||||
else:
|
||||
self.members[(chat_id, uid)] = FlatRestricted(
|
||||
until_date=until_date, user=user, **bits
|
||||
)
|
||||
return True
|
||||
|
||||
async def ban_chat_member(self, chat_id, uid, revoke_messages=False):
|
||||
self.banned.append((int(chat_id), int(uid), revoke_messages))
|
||||
return True
|
||||
|
||||
async def unban_chat_member(self, chat_id, uid, only_if_banned=False):
|
||||
self.unbanned.append((int(chat_id), int(uid), only_if_banned))
|
||||
return True
|
||||
|
||||
|
||||
class FakePlanner:
|
||||
url = "memory://planner"
|
||||
configured = True
|
||||
|
||||
def __init__(self, result=None, error=None):
|
||||
self.result = result
|
||||
self.error = error
|
||||
self.payloads = []
|
||||
|
||||
async def plan(self, payload):
|
||||
self.payloads.append(payload)
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
if callable(self.result):
|
||||
return self.result(payload)
|
||||
return self.result or mb.PlanResult("unban", TARGET_ID, 0, "", "")
|
||||
|
||||
|
||||
def make_bridge(tmp_path, bot, planner=None, admins=(ADMIN_ID,)):
|
||||
ns = {
|
||||
"bot": bot,
|
||||
"BOT_DB": str(tmp_path / "bot.sqlite3"),
|
||||
"CFG": {"newapi_db": str(tmp_path / "newapi.sqlite3")},
|
||||
"ADMIN_IDS": admins,
|
||||
}
|
||||
return mb.ModerationBridge(ns, planner=planner or FakePlanner(), clock=lambda: NOW)
|
||||
|
||||
|
||||
def admin_member():
|
||||
return Member("administrator", FakeUser(ADMIN_ID), can_restrict_members=True)
|
||||
|
||||
|
||||
def bot_admin_member():
|
||||
return Member("administrator", FakeUser(BOT_ID), can_restrict_members=True)
|
||||
|
||||
|
||||
def test_flat_restricted_bits_and_datetime_timestamp():
|
||||
until = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
|
||||
member = FlatRestricted(until_date=until, can_send_messages=True, can_invite_users=True)
|
||||
bits = mb._member_bits(member)
|
||||
assert bits["can_send_messages"] is True
|
||||
assert bits["can_invite_users"] is True
|
||||
assert bits["can_send_polls"] is False
|
||||
assert mb._as_timestamp(until) == int(until.timestamp())
|
||||
assert mb._as_timestamp(None) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seen_index_and_reply_accept_negative_chat_id(tmp_path):
|
||||
bot = FakeBot()
|
||||
bridge = make_bridge(tmp_path, bot)
|
||||
await bridge._remember(GROUP, [(TARGET_ID, "target", "Target")])
|
||||
found = await bridge.candidates_for(CHAT_ID, ["@target"])
|
||||
assert [item["uid"] for item in found] == [TARGET_ID]
|
||||
|
||||
await bridge.send_text(None, "ответ", chat=GROUP)
|
||||
assert bot.sent and bot.sent[-1]["chat_id"] == CHAT_ID
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mute_records_flat_restricted_preimage(tmp_path):
|
||||
until = datetime.fromtimestamp(NOW + 3600, tz=timezone.utc)
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): FlatRestricted(
|
||||
until_date=until, can_send_messages=True, can_invite_users=True
|
||||
),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
|
||||
reply = await bridge._group_action(message, "mute", ["10m"])
|
||||
assert isinstance(reply, str) and reply
|
||||
chat_id, uid, perms, applied_until = bot.restricted[-1]
|
||||
assert (chat_id, uid) == (CHAT_ID, TARGET_ID)
|
||||
assert perms.can_send_messages is False
|
||||
assert perms.can_invite_users is True
|
||||
assert applied_until == NOW + 600
|
||||
|
||||
receipt = await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID)
|
||||
assert receipt["preimage_kind"] == "restricted"
|
||||
assert int(receipt["preimage_until"]) == int(until.timestamp())
|
||||
assert bot.member_calls.count((CHAT_ID, TARGET_ID)) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_restores_flat_restricted_preimage(tmp_path):
|
||||
until = datetime.fromtimestamp(NOW + 3600, tz=timezone.utc)
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): FlatRestricted(
|
||||
until_date=until, can_send_messages=True, can_invite_users=True
|
||||
),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("unmute", TARGET_ID, 0, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
message = FakeMessage("/unmute", user=FakeUser(ADMIN_ID, "admin"))
|
||||
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
reply = await bridge._group_action(message, "unmute", [])
|
||||
assert isinstance(reply, str) and reply
|
||||
_, _, perms, applied_until = bot.restricted[-1]
|
||||
assert perms.can_send_messages is True
|
||||
assert perms.can_invite_users is True
|
||||
assert applied_until == int(until.timestamp())
|
||||
assert bot.member_calls.count((CHAT_ID, TARGET_ID)) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_preserves_independent_post_mute_restriction(tmp_path):
|
||||
until = datetime.fromtimestamp(NOW + 3600, tz=timezone.utc)
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): FlatRestricted(
|
||||
until_date=until, can_send_messages=True, can_invite_users=True
|
||||
),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
# An admin tightens invite rights independently after the mute.
|
||||
bot.set_member(
|
||||
CHAT_ID,
|
||||
TARGET_ID,
|
||||
FlatRestricted(
|
||||
until_date=until, can_send_messages=False, can_invite_users=False
|
||||
),
|
||||
)
|
||||
planner.result = mb.PlanResult("unmute", TARGET_ID, 0, "", "")
|
||||
reply = await bridge._group_action(message, "unmute", [])
|
||||
assert isinstance(reply, str) and reply
|
||||
_, _, perms, applied_until = bot.restricted[-1]
|
||||
assert perms.can_send_messages is True
|
||||
assert perms.can_invite_users is False
|
||||
assert applied_until == int(until.timestamp())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_reads_fresh_chat_defaults_after_tightening(tmp_path):
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): Member("member", FakeUser(TARGET_ID)),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
assert bridge._chat_defaults[CHAT_ID]["can_send_messages"] is True
|
||||
bot.chat_permissions = _perms(can_send_messages=False)
|
||||
planner.result = mb.PlanResult("unmute", TARGET_ID, 0, "", "")
|
||||
reply = await bridge._group_action(message, "unmute", [])
|
||||
assert isinstance(reply, str) and reply
|
||||
_, _, perms, _ = bot.restricted[-1]
|
||||
assert perms.can_send_messages is False
|
||||
assert perms.can_send_audios is True
|
||||
assert bridge._chat_defaults[CHAT_ID]["can_send_messages"] is False
|
||||
assert bot.chat_calls.count(CHAT_ID) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_restores_expiry_even_when_permission_bits_are_unchanged(tmp_path):
|
||||
bot = FakeBot(members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): FlatRestricted(until_date=NOW + 3600),
|
||||
})
|
||||
bridge = make_bridge(tmp_path, bot, FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", "")))
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
await bridge._group_action(message, "unmute", [])
|
||||
assert len(bot.restricted) == 2
|
||||
assert bot.restricted[-1][3] == NOW + 3600
|
||||
assert await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_expired_preimage_does_not_pin_tightened_defaults_forever(tmp_path):
|
||||
bot = FakeBot(members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): FlatRestricted(until_date=NOW + 60),
|
||||
})
|
||||
bridge = make_bridge(tmp_path, bot, FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", "")))
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
bridge.clock = lambda: NOW + 120
|
||||
bot.chat_permissions = _perms(can_send_messages=False)
|
||||
await bridge._group_action(message, "unmute", [])
|
||||
assert len(bot.restricted) == 2
|
||||
assert bot.restricted[-1][2].can_send_messages is False
|
||||
assert bot.restricted[-1][3] == NOW + 600
|
||||
assert await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unmute_does_not_restrict_an_already_unrestricted_member(tmp_path):
|
||||
bot = FakeBot(members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): Member("member", FakeUser(TARGET_ID)),
|
||||
})
|
||||
bridge = make_bridge(tmp_path, bot, FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", "")))
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
bot.set_member(CHAT_ID, TARGET_ID, Member("member", FakeUser(TARGET_ID)))
|
||||
bot.chat_permissions = _perms(can_send_messages=False)
|
||||
await bridge._group_action(message, "unmute", [])
|
||||
assert len(bot.restricted) == 1
|
||||
assert await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_protected_target_returns_the_authoritative_member(tmp_path):
|
||||
target = Member("member", FakeUser(TARGET_ID))
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): target,
|
||||
}
|
||||
)
|
||||
bridge = make_bridge(tmp_path, bot)
|
||||
returned = await bridge._protected_target(CHAT_ID, TARGET_ID, ADMIN_ID)
|
||||
assert returned is target
|
||||
assert bot.member_calls.count((CHAT_ID, TARGET_ID)) == 1
|
||||
bot.members[(CHAT_ID, TARGET_ID)] = RuntimeError("transient lookup failure")
|
||||
with pytest.raises(mb._Refusal):
|
||||
await bridge._protected_target(CHAT_ID, TARGET_ID, ADMIN_ID)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_defaults_failure_refuses_and_does_not_cache(tmp_path):
|
||||
bot = FakeBot(chat_permissions=_perms(can_send_messages=False))
|
||||
bridge = make_bridge(tmp_path, bot)
|
||||
bot.chat_error = RuntimeError("Bad Gateway")
|
||||
with pytest.raises(mb._Refusal):
|
||||
await bridge.chat_defaults(CHAT_ID)
|
||||
assert bridge._chat_defaults == {}
|
||||
bot.chat_error = None
|
||||
bits = await bridge.chat_defaults(CHAT_ID)
|
||||
assert bits["can_send_messages"] is False
|
||||
assert bridge._chat_defaults[CHAT_ID]["can_send_messages"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mute_defaults_failure_has_no_side_effects_and_retries_fresh(tmp_path):
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): Member("member", FakeUser(TARGET_ID)),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("mute", TARGET_ID, 600, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
message = FakeMessage("/mute 10m", user=FakeUser(ADMIN_ID, "admin"))
|
||||
|
||||
bot.chat_error = RuntimeError("Bad Gateway")
|
||||
with pytest.raises(mb._Refusal):
|
||||
await bridge._group_action(message, "mute", ["10m"])
|
||||
assert bot.restricted == []
|
||||
assert await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID) is None
|
||||
|
||||
bot.chat_error = None
|
||||
bot.chat_permissions = _perms(can_invite_users=False)
|
||||
reply = await bridge._group_action(message, "mute", ["10m"])
|
||||
assert isinstance(reply, str) and reply
|
||||
assert bot.restricted
|
||||
receipt = await asyncio.to_thread(mb._read_mute_receipt, bridge.bot_db, CHAT_ID, TARGET_ID)
|
||||
assert receipt["preimage_kind"] == "default"
|
||||
assert json.loads(receipt["preimage"])["can_invite_users"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_protected_target_refuses_when_member_lookup_fails(tmp_path):
|
||||
bot = FakeBot(members={(CHAT_ID, ADMIN_ID): admin_member()})
|
||||
bridge = make_bridge(tmp_path, bot)
|
||||
with pytest.raises(mb._Refusal):
|
||||
await bridge._protected_target(CHAT_ID, TARGET_ID, ADMIN_ID)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_addressed_mode_keeps_existing_name_trigger(tmp_path):
|
||||
bridge = make_bridge(tmp_path, FakeBot())
|
||||
bridge._bot_username = "iishko_bot"
|
||||
assert await bridge.chat_mode(CHAT_ID) == "addressed"
|
||||
plain = FakeMessage("Иишко, привет")
|
||||
named = FakeMessage("Иишко: привет")
|
||||
other = FakeMessage("просто привет")
|
||||
assert bridge.allow_group_message(plain) is True
|
||||
assert bridge.allow_group_message(named) is True
|
||||
assert bridge.allow_group_message(other) is False
|
||||
|
||||
|
||||
def test_install_uses_outer_middleware_and_is_idempotent(tmp_path):
|
||||
router = Router()
|
||||
ns = {"bot": FakeBot(), "BOT_DB": str(tmp_path / "bot.sqlite3"), "ADMIN_IDS": [ADMIN_ID]}
|
||||
first = mb.install(ns, router, planner=FakePlanner())
|
||||
second = mb.install(ns, router)
|
||||
assert first is second is ns["_MODERATION_BRIDGE"]
|
||||
assert len(router.message.outer_middleware) == 1
|
||||
assert len(router.chat_member.outer_middleware) == 1
|
||||
assert callable(ns["moderation_allow_group_message"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_username_resolution_fails_closed_without_planner(tmp_path):
|
||||
bridge = make_bridge(tmp_path, FakeBot(), FakePlanner(error=mb.PlannerUnavailable("down")))
|
||||
with pytest.raises(mb.PlannerUnavailable):
|
||||
await bridge.resolve_target(FakeMessage("/unban @target"), ["@target"])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_group_unban_never_touches_global_account(tmp_path, monkeypatch):
|
||||
def boom(*args, **kwargs):
|
||||
raise AssertionError("account_admin must not be called for group /unban")
|
||||
|
||||
monkeypatch.setattr(account_admin, "unban_account", boom)
|
||||
bot = FakeBot(
|
||||
members={
|
||||
(CHAT_ID, ADMIN_ID): admin_member(),
|
||||
(CHAT_ID, BOT_ID): bot_admin_member(),
|
||||
(CHAT_ID, TARGET_ID): Member("kicked", FakeUser(TARGET_ID)),
|
||||
}
|
||||
)
|
||||
planner = FakePlanner(mb.PlanResult("unban", TARGET_ID, 0, "", ""))
|
||||
bridge = make_bridge(tmp_path, bot, planner)
|
||||
await bridge._group_action(FakeMessage("/unban"), "unban", [])
|
||||
assert bot.unbanned[-1] == (CHAT_ID, TARGET_ID, True)
|
||||
@@ -0,0 +1,404 @@
|
||||
"""Preheader-timeout fix for large generation POSTs; loopback only, no external network.
|
||||
|
||||
Module under test: transparent_api.py from IISHKO_SNAPSHOT_ROOT (default
|
||||
../gateway relative to this file). Twelve cases: helper invariants (caller
|
||||
total/connect/sock_connect/ceil_threshold preserved, scope gating), real
|
||||
slow-headers loopback for a big POST vs small POST/GET, an explicit shorter
|
||||
caller total, body idle re-applied after headers (JSON + connector release,
|
||||
SSE stall, provider error body), no replay after a preheader timeout, bounded
|
||||
recovery-waiter cleanup under cancellation, and one safe-429 recovery whose
|
||||
generation bytes stay exact.
|
||||
"""
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
|
||||
ROOT = Path(os.environ.get('IISHKO_SNAPSHOT_ROOT',
|
||||
str(Path(__file__).resolve().parents[1] / 'gateway')))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
_spec = importlib.util.spec_from_file_location('prefill_relay', ROOT / 'transparent_api.py')
|
||||
if _spec is None or _spec.loader is None:
|
||||
raise RuntimeError('cannot load transparent_api from the required snapshot')
|
||||
relay = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(relay)
|
||||
|
||||
GEN = '/v1/chat/completions'
|
||||
MODEL = 'test-model'
|
||||
IDLE = 0.15 # inherited socket idle budget, scaled down for loopback
|
||||
SLOW = 0.4 # header/body delay that must exceed IDLE
|
||||
BIG_BODY = (b'{"model":"' + MODEL.encode() + b'","messages":[{"role":"user","content":"'
|
||||
+ b'x' * relay.PREFILL_MIN_BODY + b'"}]}')
|
||||
SMALL_BODY = b'{"model":"test-model","messages":[{"role":"user","content":"hi"}]}'
|
||||
JSON_OK = json.dumps({
|
||||
'model': MODEL,
|
||||
'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': 'OK'},
|
||||
'finish_reason': 'stop'}],
|
||||
}).encode()
|
||||
BUSY_429 = json.dumps({
|
||||
'error': {'message': 'upstream capacity temporarily exhausted',
|
||||
'type': 'upstream_error', 'code': 'upstream_busy',
|
||||
'status': 429, 'retryable': True},
|
||||
}).encode()
|
||||
TIMEOUTS = (asyncio.TimeoutError, aiohttp.ClientError)
|
||||
|
||||
|
||||
class _Transport:
|
||||
def is_closing(self):
|
||||
return False
|
||||
|
||||
|
||||
class FakeRequest:
|
||||
"""Only the attributes relay_api_request/relay_api touch off the wire."""
|
||||
|
||||
def __init__(self, method='POST', path=GEN, headers=None, transport=None):
|
||||
self.method = method
|
||||
self.path = path
|
||||
self.headers = headers if headers is not None else {'Authorization': 'Bearer sk-test'}
|
||||
self.transport = _Transport() if transport is None else transport
|
||||
|
||||
|
||||
class PrefillHelperTests(unittest.TestCase):
|
||||
def test_constants_and_scope_gating(self):
|
||||
self.assertEqual(relay.PREFILL_SOCK_READ, 180.0)
|
||||
self.assertEqual(relay.PREFILL_MIN_BODY, 64 * 1024)
|
||||
big = b'x' * relay.PREFILL_MIN_BODY
|
||||
self.assertTrue(relay._extended_prefill(FakeRequest(), big))
|
||||
self.assertTrue(relay._extended_prefill(FakeRequest(path=GEN + '/'), memoryview(big)))
|
||||
self.assertFalse(relay._extended_prefill(FakeRequest(), big[:-1]),
|
||||
'below the prefill threshold the inherited socket budget stays')
|
||||
self.assertFalse(relay._extended_prefill(FakeRequest(method='GET'), big))
|
||||
self.assertFalse(relay._extended_prefill(FakeRequest(path='/v1/models'), big),
|
||||
'non-generation paths must not get the prefill budget')
|
||||
self.assertFalse(relay._extended_prefill(FakeRequest(), big.decode()))
|
||||
self.assertFalse(relay._extended_prefill(FakeRequest(), b''))
|
||||
|
||||
def test_derived_timeout_preserves_caller_budget(self):
|
||||
original = aiohttp.ClientTimeout(total=None, connect=7.0, sock_connect=3.0,
|
||||
sock_read=45.0, ceil_threshold=9)
|
||||
derived = relay._prefill_timeout(original)
|
||||
self.assertIsNot(derived, original)
|
||||
self.assertEqual(derived.sock_read, 180.0)
|
||||
self.assertIsNone(derived.total, 'caller total must not be widened')
|
||||
self.assertEqual(derived.connect, 7.0)
|
||||
self.assertEqual(derived.sock_connect, 3.0)
|
||||
self.assertEqual(derived.ceil_threshold, 9,
|
||||
'ceil_threshold must be carried over, not reset to the default')
|
||||
capped = aiohttp.ClientTimeout(total=120.0, sock_read=45.0)
|
||||
self.assertEqual(relay._prefill_timeout(capped).sock_read, 120.0,
|
||||
'an explicit caller total caps the derived read budget')
|
||||
for untouched in (
|
||||
aiohttp.ClientTimeout(total=30.0, sock_read=45.0), # total below sock_read
|
||||
aiohttp.ClientTimeout(total=None, sock_read=300.0), # already generous
|
||||
aiohttp.ClientTimeout(total=60.0, sock_read=None), # no read budget
|
||||
aiohttp.ClientTimeout(total=None, sock_read=float('inf')),
|
||||
):
|
||||
self.assertIs(relay._prefill_timeout(untouched), untouched)
|
||||
|
||||
|
||||
class SlowLoopbackTests(unittest.IsolatedAsyncioTestCase):
|
||||
"""Real aiohttp client/server: slow headers must not be cut at sock_read."""
|
||||
|
||||
async def start(self, handler, path=GEN):
|
||||
app = web.Application()
|
||||
app.router.add_route('*', path, handler)
|
||||
server = TestServer(app)
|
||||
await server.start_server()
|
||||
self.addAsyncCleanup(server.close)
|
||||
return server
|
||||
|
||||
async def session(self, total, sock_read):
|
||||
client = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=total, sock_read=sock_read))
|
||||
self.addAsyncCleanup(client.close)
|
||||
return client
|
||||
|
||||
async def test_big_post_survives_headers_slower_than_socket_idle(self):
|
||||
calls = []
|
||||
|
||||
async def upstream(request):
|
||||
calls.append(await request.read())
|
||||
await asyncio.sleep(SLOW)
|
||||
return web.Response(body=JSON_OK, content_type='application/json')
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(5.0, IDLE)
|
||||
response = await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN), headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.body, JSON_OK, 'generation bytes must be exact')
|
||||
self.assertEqual(calls, [BIG_BODY], 'the upstream must receive the body unchanged')
|
||||
|
||||
async def test_small_post_and_get_keep_the_original_socket_idle(self):
|
||||
async def upstream(request):
|
||||
await asyncio.sleep(SLOW)
|
||||
return web.Response(body=JSON_OK, content_type='application/json')
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(5.0, IDLE)
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TIMEOUTS):
|
||||
await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=SMALL_BODY, requested_model=MODEL)
|
||||
self.assertLess(time.monotonic() - started, SLOW,
|
||||
'a small POST must still be cut at the inherited socket idle')
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TIMEOUTS):
|
||||
await relay.relay_api_request(
|
||||
FakeRequest(method='GET'), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'}, body=b'', requested_model=None)
|
||||
self.assertLess(time.monotonic() - started, SLOW,
|
||||
'a GET must still be cut at the inherited socket idle')
|
||||
|
||||
async def test_explicit_shorter_total_bounds_the_prefill_wait(self):
|
||||
async def upstream(request):
|
||||
await request.read()
|
||||
await asyncio.sleep(SLOW)
|
||||
return web.Response(body=JSON_OK, content_type='application/json')
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(0.25, IDLE)
|
||||
self.assertLessEqual(relay._prefill_timeout(client.timeout).sock_read, 0.25,
|
||||
'caller total caps the derived read budget')
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(TIMEOUTS):
|
||||
await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL)
|
||||
self.assertLess(time.monotonic() - started, SLOW,
|
||||
'an explicit shorter total must still end the wait')
|
||||
|
||||
async def test_body_idle_is_re_applied_after_headers_and_connector_released(self):
|
||||
release = asyncio.Event()
|
||||
|
||||
async def upstream(request):
|
||||
await request.read()
|
||||
response = web.StreamResponse(headers={'Content-Type': 'application/json'})
|
||||
await response.prepare(request) # headers are already on the wire
|
||||
await release.wait()
|
||||
await response.write(JSON_OK)
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(5.0, IDLE)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with self.assertRaises(TIMEOUTS):
|
||||
await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL)
|
||||
self.assertLess(time.monotonic() - started, SLOW,
|
||||
'post-header body idle must be the inherited budget, not 180s')
|
||||
acquired = getattr(client.connector, '_acquired', None)
|
||||
if acquired is not None:
|
||||
self.assertEqual(len(acquired), 0,
|
||||
'an aborted body must not keep a leased connection')
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
async def test_preheader_timeout_is_not_replayed(self):
|
||||
calls = []
|
||||
|
||||
async def upstream(request):
|
||||
calls.append(1)
|
||||
await asyncio.sleep(SLOW)
|
||||
return web.Response(body=JSON_OK, content_type='application/json')
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(0.2, IDLE)
|
||||
with self.assertRaises(TIMEOUTS):
|
||||
await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL)
|
||||
await asyncio.sleep(SLOW)
|
||||
self.assertEqual(len(calls), 1, 'an ambiguous preheader timeout must never be replayed')
|
||||
|
||||
async def test_safe_429_recovers_once_without_touching_bytes(self):
|
||||
calls = []
|
||||
|
||||
async def upstream(request):
|
||||
await request.read()
|
||||
calls.append(1)
|
||||
if len(calls) == 1:
|
||||
await asyncio.sleep(SLOW) # a busy answer may also arrive after a long prefill
|
||||
return web.Response(body=BUSY_429, status=429, content_type='application/json')
|
||||
return web.Response(body=JSON_OK, content_type='application/json')
|
||||
|
||||
server = await self.start(upstream)
|
||||
client = await self.session(5.0, IDLE)
|
||||
response = await relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL)
|
||||
self.assertEqual(len(calls), 2, 'one definitive pre-generation busy 429 is recoverable')
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(response.body, JSON_OK, 'recovered generation must stay byte-exact')
|
||||
|
||||
|
||||
class StreamBodyIdleTests(unittest.IsolatedAsyncioTestCase):
|
||||
"""Body idle after headers on the streaming/error paths, through a real proxy."""
|
||||
|
||||
async def proxy_run(self, upstream_handler, *, path=GEN, idle=IDLE):
|
||||
calls = []
|
||||
|
||||
async def upstream(request):
|
||||
calls.append(await request.read())
|
||||
return await upstream_handler(request)
|
||||
|
||||
upstream_app = web.Application()
|
||||
upstream_app.router.add_route('*', path, upstream)
|
||||
server = TestServer(upstream_app)
|
||||
await server.start_server()
|
||||
self.addAsyncCleanup(server.close)
|
||||
session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5, sock_read=180))
|
||||
self.addAsyncCleanup(session.close)
|
||||
url = server.make_url(path)
|
||||
|
||||
async def proxy(request):
|
||||
try:
|
||||
async with session.request('POST', url, data=await request.read(),
|
||||
headers={'Authorization': 'Bearer sk-test'}) as response:
|
||||
return await relay.relay_api(request, response, requested_model=MODEL,
|
||||
body_idle_timeout=idle)
|
||||
except TIMEOUTS:
|
||||
return web.Response(status=504, body=b'')
|
||||
|
||||
proxy_app = web.Application()
|
||||
proxy_app.router.add_post(path, proxy)
|
||||
runner = web.AppRunner(proxy_app)
|
||||
await runner.setup()
|
||||
site = web.TCPSite(runner, '127.0.0.1', 0)
|
||||
await site.start()
|
||||
self.addAsyncCleanup(runner.cleanup)
|
||||
port = site._server.sockets[0].getsockname()[1]
|
||||
return port, calls
|
||||
|
||||
async def test_sse_body_idle_is_explicit_nonretryable_incomplete(self):
|
||||
release = asyncio.Event()
|
||||
partial = (b'data: ' + json.dumps({'model': MODEL, 'choices': [
|
||||
{'delta': {'content': 'partial'}}]}).encode() + b'\n\n')
|
||||
|
||||
async def upstream(request):
|
||||
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
await response.write(partial)
|
||||
await release.wait()
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
port, calls = await self.proxy_run(upstream)
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as client:
|
||||
async with client.post('http://127.0.0.1:%d%s' % (port, GEN),
|
||||
data=b'{"stream":true}') as response:
|
||||
status, body = response.status, await response.read()
|
||||
self.assertEqual(status, 200)
|
||||
self.assertTrue(body.startswith(partial), 'received frames stay byte-exact')
|
||||
self.assertIn(b'upstream_stream_incomplete', body)
|
||||
self.assertNotIn(b'[DONE]', body)
|
||||
self.assertEqual(len(calls), 1, 'a stalled body must never be replayed')
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
async def test_sse_idle_wrapper_keeps_complete_stream_byte_exact(self):
|
||||
frames = (b'data: ' + json.dumps({'model': MODEL, 'choices': [
|
||||
{'delta': {'content': 'A'}}]}).encode() + b'\n\n'
|
||||
b'data: ' + json.dumps({'model': MODEL, 'choices': [
|
||||
{'delta': {}, 'finish_reason': 'stop'}]}).encode() + b'\n\ndata: [DONE]\n\n')
|
||||
|
||||
async def upstream(request):
|
||||
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
for index in range(0, len(frames), 64):
|
||||
await response.write(frames[index:index + 64])
|
||||
await asyncio.sleep(0.005)
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
port, calls = await self.proxy_run(upstream)
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as client:
|
||||
async with client.post('http://127.0.0.1:%d%s' % (port, GEN),
|
||||
data=b'{"stream":true}') as response:
|
||||
status, body = response.status, await response.read()
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(body, frames, 'idle wrapping must not alter forwarded bytes')
|
||||
self.assertEqual(len(calls), 1)
|
||||
|
||||
async def test_error_body_idle_ends_as_504_without_leaking_partial(self):
|
||||
release = asyncio.Event()
|
||||
|
||||
async def upstream(request):
|
||||
response = web.StreamResponse(status=429,
|
||||
headers={'Content-Type': 'application/json'})
|
||||
await response.prepare(request)
|
||||
await response.write(b'{"error":{"message":"partial')
|
||||
await release.wait()
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
port, calls = await self.proxy_run(upstream)
|
||||
try:
|
||||
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as client:
|
||||
async with client.post('http://127.0.0.1:%d%s' % (port, GEN),
|
||||
data=b'{"stream":true}') as response:
|
||||
status, body = response.status, await response.read()
|
||||
self.assertEqual(status, 504)
|
||||
self.assertEqual(body, b'', 'a partial provider error must not leak downstream')
|
||||
self.assertEqual(len(calls), 1)
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
class WaiterCleanupTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_cancellation_leaves_no_reserved_recovery_slot(self):
|
||||
async def upstream(request):
|
||||
await request.read()
|
||||
return web.Response(body=BUSY_429, status=429, content_type='application/json',
|
||||
headers={'Retry-After': '2'})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_post(GEN, upstream)
|
||||
server = TestServer(app)
|
||||
await server.start_server()
|
||||
self.addAsyncCleanup(server.close)
|
||||
client = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30, sock_read=30))
|
||||
self.addAsyncCleanup(client.close)
|
||||
|
||||
task = asyncio.create_task(relay.relay_api_request(
|
||||
FakeRequest(), client, server.make_url(GEN),
|
||||
headers={'Authorization': 'Bearer sk-test'},
|
||||
body=BIG_BODY, requested_model=MODEL))
|
||||
slot = None
|
||||
for _ in range(400):
|
||||
await asyncio.sleep(0.01)
|
||||
held = [entry for entry in relay._BUSY_WAITERS.values() if entry.total]
|
||||
if held:
|
||||
slot = held[0]
|
||||
break
|
||||
if task.done():
|
||||
break
|
||||
self.assertIsNotNone(slot, 'the sleep between busy retries must hold one bounded slot')
|
||||
task.cancel()
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await task
|
||||
for entry in relay._BUSY_WAITERS.values():
|
||||
self.assertEqual(entry.total, 0,
|
||||
'a cancelled recovery must release every waiter slot')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Downstream-outcome accounting for the provider relay.
|
||||
|
||||
An upstream 200 is not success by itself: the identity, payload, and validation
|
||||
layers can still turn it into a downstream 5xx. These tests pin the contract --
|
||||
account the status the caller actually received, credit one route once, never
|
||||
replay after streaming started, and never penalize client cancellation or a
|
||||
client-side refusal.
|
||||
"""
|
||||
import asyncio
|
||||
from contextlib import closing
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway' if (ROOT / 'gateway').is_dir() else ROOT))
|
||||
from gateway_provider_relay import relay_selected
|
||||
from gateway_providers import ProviderRegistry
|
||||
|
||||
MODEL = 'exact-model'
|
||||
|
||||
|
||||
def configuration():
|
||||
return {'pinning_enabled': True, 'providers': [
|
||||
{'id': 'primary', 'name': 'Primary', 'channel_ids': [1], 'max_inflight': 1,
|
||||
'models': {MODEL: {'effort_levels': None}}},
|
||||
{'id': 'reserve', 'name': 'Reserve', 'channel_ids': [2], 'reserve': True,
|
||||
'models': {MODEL: {'effort_levels': None}}}]}
|
||||
|
||||
|
||||
class _Content:
|
||||
def __init__(self, chunks=()):
|
||||
self._chunks = chunks
|
||||
|
||||
async def iter_chunked(self, size):
|
||||
for chunk in self._chunks:
|
||||
yield chunk
|
||||
|
||||
|
||||
class _Reply:
|
||||
def __init__(self, status, *, headers=None, chunks=()):
|
||||
self.status = status
|
||||
self.headers = dict(headers or {})
|
||||
self.content = _Content(chunks)
|
||||
|
||||
|
||||
class _Exchange:
|
||||
def __init__(self, reply):
|
||||
self.reply = reply
|
||||
|
||||
async def __aenter__(self):
|
||||
return self.reply
|
||||
|
||||
async def __aexit__(self, *exc_info):
|
||||
return False
|
||||
|
||||
|
||||
class Upstream:
|
||||
|
||||
def __init__(self, replies):
|
||||
self.replies = list(replies)
|
||||
self.authorizations = []
|
||||
|
||||
def request(self, method, target, **kwargs):
|
||||
self.authorizations.append(kwargs['headers'].get('Authorization'))
|
||||
return _Exchange(self.replies.pop(0))
|
||||
|
||||
|
||||
class Request(dict):
|
||||
def __init__(self, headers=None):
|
||||
super().__init__()
|
||||
self.method = 'POST'
|
||||
self.headers = dict(headers or {})
|
||||
self.transport = None
|
||||
|
||||
|
||||
class RelayOutcomeAccountingTests(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.db = str(Path(self.tmp.name) / 'newapi.db')
|
||||
with closing(sqlite3.connect(self.db)) as con, con:
|
||||
con.executescript(
|
||||
'CREATE TABLE users(id INTEGER PRIMARY KEY,role INTEGER,status INTEGER,deleted_at INTEGER);'
|
||||
'CREATE TABLE tokens(key TEXT,user_id INTEGER,"group" TEXT,status INTEGER,deleted_at INTEGER);'
|
||||
'CREATE TABLE channels(id INTEGER PRIMARY KEY,status INTEGER,model_mapping TEXT);'
|
||||
'CREATE TABLE abilities(channel_id INTEGER,model TEXT,enabled INTEGER,"group" TEXT);')
|
||||
con.execute('INSERT INTO users VALUES(1,100,1,NULL)')
|
||||
con.execute('INSERT INTO tokens VALUES("testkey",1,"default",1,NULL)')
|
||||
con.executemany('INSERT INTO channels VALUES(?,1,"{}")', [(1,), (2,)])
|
||||
con.executemany('INSERT INTO abilities VALUES(?,"exact-model",1,"default")', [(1,), (2,)])
|
||||
self.registry = ProviderRegistry(configuration(), clock=lambda: 1000.0)
|
||||
self.body = json.dumps({'model': MODEL}).encode()
|
||||
|
||||
async def relay(self, upstream, success, failure=None):
|
||||
async def default_failure(status, raw, outgoing):
|
||||
return web.Response(status=status, body=raw, content_type='application/json')
|
||||
return await relay_selected(Request(), upstream, 'http://upstream/v1/messages',
|
||||
headers={}, body=self.body, registry=self.registry,
|
||||
newapi_db=self.db, raw_key='testkey', model=MODEL,
|
||||
success=success, failure=failure or default_failure)
|
||||
|
||||
def failures(self, channel):
|
||||
return self.registry._circuits.get((channel, MODEL), {}).get('failures', 0)
|
||||
|
||||
def assert_idle(self):
|
||||
self.assertEqual(sum(self.registry._active.values()), 0)
|
||||
|
||||
async def test_downstream_503_from_upstream_200_counts_one_failure_and_no_retry(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
return web.Response(status=503, body=b'{"error":{"code":"model_identity_mismatch"}}')
|
||||
|
||||
result = await self.relay(upstream, success)
|
||||
self.assertEqual(result.status, 503)
|
||||
self.assertEqual(upstream.authorizations, ['Bearer sk-testkey-1'])
|
||||
self.assertEqual(self.failures(1), 1)
|
||||
self.assert_idle()
|
||||
|
||||
async def test_healthy_downstream_200_is_recorded_as_success(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
return web.Response(status=200, body=b'ok')
|
||||
|
||||
result = await self.relay(upstream, success)
|
||||
self.assertEqual(result.status, 200)
|
||||
self.assertEqual(self.registry._circuits, {})
|
||||
self.assertEqual(len(upstream.authorizations), 1)
|
||||
self.assert_idle()
|
||||
|
||||
async def test_statusless_handler_falls_back_to_the_upstream_status(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
return None
|
||||
|
||||
self.assertIsNone(await self.relay(upstream, success))
|
||||
self.assertEqual(self.registry._circuits, {})
|
||||
self.assert_idle()
|
||||
|
||||
async def test_throttled_rejection_falls_back_once_and_both_routes_are_accounted(self):
|
||||
body = b'{"error":{"code":"upstream_throttled"}}'
|
||||
headers = {'Content-Type': 'application/json', 'Retry-After': '20'}
|
||||
upstream = Upstream([_Reply(429, headers=headers, chunks=[body]),
|
||||
_Reply(429, headers=headers, chunks=[body])])
|
||||
|
||||
async def success(response):
|
||||
self.fail('a rejected attempt must never be treated as success')
|
||||
|
||||
result = await self.relay(upstream, success)
|
||||
self.assertEqual(result.status, 429)
|
||||
self.assertEqual(upstream.authorizations, ['Bearer sk-testkey-1', 'Bearer sk-testkey-2'])
|
||||
self.assertEqual((self.failures(1), self.failures(2)), (1, 1))
|
||||
self.assert_idle()
|
||||
|
||||
async def test_client_cancellation_is_not_penalized_and_releases_the_lease(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
raise asyncio.CancelledError()
|
||||
|
||||
with self.assertRaises(asyncio.CancelledError):
|
||||
await self.relay(upstream, success)
|
||||
self.assertEqual(self.registry._circuits, {})
|
||||
self.assertEqual(len(upstream.authorizations), 1)
|
||||
self.assert_idle()
|
||||
|
||||
async def test_ambiguous_stream_error_is_not_replayed(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
raise aiohttp.ClientPayloadError('stream interrupted')
|
||||
|
||||
with self.assertRaises(aiohttp.ClientPayloadError):
|
||||
await self.relay(upstream, success)
|
||||
self.assertEqual(len(upstream.authorizations), 1)
|
||||
self.assertEqual(self.failures(1), 1)
|
||||
self.assert_idle()
|
||||
|
||||
async def test_client_side_refusal_does_not_open_a_provider_circuit(self):
|
||||
upstream = Upstream([_Reply(200)])
|
||||
|
||||
async def success(response):
|
||||
return web.Response(status=400, body=b'{"error":{"code":"invalid_request"}}')
|
||||
|
||||
result = await self.relay(upstream, success)
|
||||
self.assertEqual(result.status, 400)
|
||||
self.assertEqual(self.registry._circuits, {})
|
||||
self.assert_idle()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Acceptance tests for candidate/rankings.py (stdlib unittest; pytest-compatible).
|
||||
|
||||
Run from the task root: python -m unittest -v test_rankings
|
||||
Fixtures are disposable sqlite files shaped like production bot.db / one-api logs.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "bot"))
|
||||
|
||||
import rankings
|
||||
|
||||
NOW = 1_790_000_000 # fixed instant, well inside fixtures' ranges
|
||||
DAY = 86400
|
||||
|
||||
|
||||
def make_bot_db(path, users):
|
||||
con = sqlite3.connect(path)
|
||||
con.execute(
|
||||
"CREATE TABLE users (tg_id INTEGER PRIMARY KEY, username TEXT, referred_by INTEGER, "
|
||||
"ref_time INTEGER, ref_awarded INTEGER DEFAULT 0, banned INTEGER DEFAULT 0, "
|
||||
"api_blocked INTEGER DEFAULT 0)")
|
||||
con.executemany(
|
||||
"INSERT INTO users (tg_id, username, referred_by, ref_time, ref_awarded, banned, api_blocked) "
|
||||
"VALUES (?,?,?,?,?,?,?)", users)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def make_gw_db(path, logs):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
con = sqlite3.connect(path)
|
||||
con.execute(
|
||||
"CREATE TABLE logs (id INTEGER PRIMARY KEY AUTOINCREMENT, type INTEGER, created_at INTEGER, "
|
||||
"token_name TEXT, model_name TEXT, quota INTEGER, prompt_tokens INTEGER, completion_tokens INTEGER)")
|
||||
con.execute("CREATE INDEX idx_created_at_type ON logs(created_at, type)")
|
||||
con.executemany(
|
||||
"INSERT INTO logs (type, created_at, token_name, model_name, quota, prompt_tokens, completion_tokens) "
|
||||
"VALUES (?,?,?,?,?,?,?)", logs)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.dir = Path(self.tmp.name)
|
||||
self.bot = self.dir / "bot.db"
|
||||
self.gw = self.dir / "oneapi.db"
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def call(self, kind="referrals", period=None, **kwargs):
|
||||
return rankings.top(self.bot, self.gw, kind=kind, period=period, now=NOW, **kwargs)
|
||||
|
||||
|
||||
class ReferralTests(Base):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
users = [
|
||||
(100, "alice", None, None, 0, 0, 0),
|
||||
(200, "bob", None, None, 0, 0, 0),
|
||||
(300, None, None, None, 0, 0, 0), # referrer without public username
|
||||
(400, "carol", None, None, 0, 1, 0),
|
||||
(500, "dave", None, None, 0, 0, 0),
|
||||
(600, "erin", None, None, 0, 0, 1), # api_blocked referrer
|
||||
# referred users
|
||||
(1, "old1", 100, NOW - 100, 1, 0, 0),
|
||||
(2, "old2", 100, NOW - 200, 1, 0, 0),
|
||||
(3, "old3", 100, NOW - 300, 1, 0, 0),
|
||||
(9_000_000_001, "new1", 100, NOW - 400, 1, 0, 0),
|
||||
(10, "b1", 200, NOW - 500, 1, 0, 0),
|
||||
(11, "b2", 200, NOW - 600, 1, 0, 0),
|
||||
(12, "c1", 400, NOW - 700, 1, 0, 0),
|
||||
(13, "d1", 500, NOW - 40 * DAY, 1, 0, 0),
|
||||
(14, "e1", 600, NOW - 800, 1, 0, 0),
|
||||
(15, "n1", 300, NOW - 900, 1, 0, 0),
|
||||
(16, "not_awarded", 200, NOW - 1000, 0, 0, 0),
|
||||
]
|
||||
make_bot_db(self.bot, users)
|
||||
|
||||
def test_default_is_lifetime_weighted_referrals(self):
|
||||
data = self.call(period=None)
|
||||
self.assertEqual(data["period"], "all")
|
||||
self.assertIsNone(data["from_ts"])
|
||||
self.assertEqual(data["kind"], "referrals")
|
||||
self.assertEqual(data["value"], "weighted_refs")
|
||||
self.assertEqual([r["user"] for r in data["top"]],
|
||||
["@alice", "@bob", data["top"][2]["user"], "@dave"])
|
||||
alice = data["top"][0]
|
||||
self.assertEqual(alice["pos"], 1)
|
||||
self.assertEqual(alice["value"], 3.5) # 3 old (1.0) + 1 new id (0.5)
|
||||
self.assertEqual(alice["refs"], alice["value"])
|
||||
self.assertEqual(alice["count"], 4)
|
||||
self.assertEqual(data["top"][1]["value"], 2.0) # only awarded referrals
|
||||
self.assertEqual(data["top"][1]["count"], 2)
|
||||
self.assertTrue(data["truncated"] is False)
|
||||
self.assertGreaterEqual(data["ranked"], 3)
|
||||
|
||||
def test_banned_and_blocked_referrers_excluded(self):
|
||||
names = [r["user"] for r in self.call(period="week")["top"]]
|
||||
self.assertNotIn("@carol", names)
|
||||
self.assertNotIn("@erin", names) # api_blocked in any window
|
||||
self.assertNotIn("@dave", names) # only out-of-window referral
|
||||
everything = [r["user"] for r in self.call(period=None)["top"]]
|
||||
self.assertNotIn("@carol", everything)
|
||||
self.assertNotIn("@erin", everything)
|
||||
|
||||
def test_week_window_filters_by_ref_time(self):
|
||||
data = self.call(period="week")
|
||||
self.assertEqual(data["from_ts"], NOW - 7 * DAY)
|
||||
self.assertEqual(data["to_ts"], NOW)
|
||||
self.assertEqual([r["user"] for r in data["top"]], ["@alice", "@bob", data["top"][2]["user"]])
|
||||
self.assertEqual(data["top"][0]["value"], 3.5)
|
||||
month = self.call(period="month")
|
||||
self.assertEqual([r["user"] for r in month["top"]][:2], ["@alice", "@bob"])
|
||||
|
||||
def test_missing_username_is_stable_pseudonym_not_uid(self):
|
||||
row = [r for r in self.call(period=None)["top"] if r["value"] == 1.0][0]
|
||||
self.assertRegex(row["user"], r"\Auser-[0-9a-f]{8}\Z")
|
||||
again = [r for r in self.call(period=None)["top"] if r["value"] == 1.0][0]
|
||||
self.assertEqual(row["user"], again["user"])
|
||||
self.assertNotEqual(row["user"], "300")
|
||||
self.assertNotIn("id300", row["user"])
|
||||
|
||||
|
||||
class UsageTests(Base):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
make_bot_db(self.bot, [
|
||||
(100, "alice", None, None, 0, 0, 0),
|
||||
(200, "bob", None, None, 0, 0, 0),
|
||||
(300, "carol", None, None, 0, 0, 0),
|
||||
(400, "banned", None, None, 0, 1, 0),
|
||||
(500, "blocked", None, None, 0, 0, 1),
|
||||
(1000, "tenant", None, None, 0, 0, 0),
|
||||
])
|
||||
logs = []
|
||||
for _ in range(5):
|
||||
logs.append((2, NOW - 100, "tg100", "gpt-x", 10, 10, 10))
|
||||
logs.append((2, NOW - 200, "tg200", "gpt-x", 10, 1000, 0))
|
||||
logs.append((2, NOW - 300, "tg300", "gpt-x", 10, 5, 5))
|
||||
logs.append((2, NOW - 400, "tg400", "gpt-x", 10, 7, 7))
|
||||
logs.append((2, NOW - 500, "tg500", "gpt-x", 10, 7, 7)) # api_blocked
|
||||
logs.append((1, NOW - 600, "tg100", "gpt-x", 10, 999, 999)) # type=1 not billing
|
||||
logs.append((2, NOW - 700, "other-tenant", "gpt-x", 10, 100, 100))
|
||||
logs.append((2, NOW - 8 * DAY, "tg100", "gpt-x", 10, 10, 10)) # outside week
|
||||
logs.append((2, NOW - 20 * DAY, "tg100", "gpt-x", 10, 10, 10)) # month only
|
||||
make_gw_db(self.gw, logs)
|
||||
|
||||
def test_requests_ordering_and_tokens_ordering_differ(self):
|
||||
requests = self.call("requests", "week")
|
||||
tokens = self.call("tokens", "week")
|
||||
self.assertEqual(requests["value"], "requests")
|
||||
self.assertEqual(tokens["value"], "tokens")
|
||||
self.assertEqual([r["user"] for r in requests["top"][:2]], ["@alice", "@bob"])
|
||||
self.assertEqual(requests["top"][0]["value"], 5)
|
||||
self.assertEqual(requests["top"][0]["requests"], 5)
|
||||
self.assertEqual([r["user"] for r in tokens["top"][:2]], ["@bob", "@alice"])
|
||||
self.assertEqual(tokens["top"][0]["value"], 1000)
|
||||
self.assertEqual(tokens["top"][0]["known_tokens"], 1000)
|
||||
self.assertTrue(tokens["top"][0]["tokens_complete"])
|
||||
self.assertEqual(tokens["top"][0]["value_kind"], "exact")
|
||||
self.assertEqual(tokens["top"][0]["tokens"], 1000)
|
||||
|
||||
def test_blocked_identities_excluded_from_both_user_boards(self):
|
||||
for kind in ("requests", "tokens"):
|
||||
names = [r["user"] for r in self.call(kind, "week")["top"]]
|
||||
self.assertNotIn("@banned", names)
|
||||
self.assertNotIn("@blocked", names)
|
||||
self.assertIn("@alice", names)
|
||||
|
||||
def test_main_and_additional_keys_merge_exact_ownership(self):
|
||||
make_gw_db(self.gw, [
|
||||
(2, NOW - 10, "tg100", "m", 1, 10, 0),
|
||||
(2, NOW - 20, "tg100-k2", "m", 1, 20, 0),
|
||||
(2, NOW - 30, "tg100-k10", "m", 1, 30, 0),
|
||||
(2, NOW - 40, "tg1009", "m", 1, 1, 0), # different uid, tiny usage
|
||||
(2, NOW - 50, "tg0100", "m", 1, 1000, 0), # leading zero: not uid 100
|
||||
(2, NOW - 60, "tg100-k0", "m", 1, 1000, 0), # invalid suffix
|
||||
(2, NOW - 70, "xtg100", "m", 1, 1000, 0), # no arbitrary prefix
|
||||
(2, NOW - 80, "tg100-k2x", "m", 1, 1000, 0), # malformed suffix
|
||||
])
|
||||
row = self.call("tokens", "week")["top"][0]
|
||||
self.assertEqual(row["user"], "@alice")
|
||||
self.assertEqual(row["requests"], 3)
|
||||
self.assertEqual(row["known_tokens"], 60)
|
||||
self.assertEqual(row["value"], 60)
|
||||
|
||||
def test_unknown_and_negative_counters_are_lower_bound(self):
|
||||
make_gw_db(self.gw, [
|
||||
(2, NOW - 10, "tg100", "m", 1, None, 5),
|
||||
(2, NOW - 20, "tg100", "m", 1, 10, 10),
|
||||
(2, NOW - 30, "tg200", "m", 1, -1, 100),
|
||||
(2, NOW - 40, "tg300", "m", 1, 5, 5),
|
||||
])
|
||||
data = self.call("tokens", "week")
|
||||
rows = {r["user"]: r for r in data["top"]}
|
||||
alice = rows["@alice"]
|
||||
self.assertEqual(alice["requests"], 2)
|
||||
self.assertEqual(alice["known_tokens"], 20)
|
||||
self.assertEqual(alice["unknown_token_requests"], 1)
|
||||
self.assertIsNone(alice["tokens"])
|
||||
self.assertFalse(alice["tokens_complete"])
|
||||
self.assertEqual(alice["value_kind"], "lower_bound")
|
||||
self.assertEqual(alice["value"], 20)
|
||||
bob = rows["@bob"]
|
||||
self.assertEqual(bob["known_tokens"], 0) # negative counter is not subtracted
|
||||
self.assertEqual(bob["unknown_token_requests"], 1)
|
||||
self.assertIsNone(bob["tokens"])
|
||||
carol = rows["@carol"]
|
||||
self.assertEqual(carol["value_kind"], "exact")
|
||||
self.assertEqual(carol["tokens"], 10)
|
||||
# requests board keeps exact request count but still reports the unknown counters
|
||||
req = {r["user"]: r for r in self.call("requests", "week")["top"]}["@alice"]
|
||||
self.assertEqual(req["value"], 2)
|
||||
self.assertIsNone(req["tokens"])
|
||||
|
||||
def test_model_aggregate_public_usage_only(self):
|
||||
data = self.call("models", "week")
|
||||
self.assertEqual(data["value"], "requests")
|
||||
self.assertEqual(data["source"], "gateway.logs(type=2).model_name")
|
||||
self.assertEqual(len(data["top"]), 1) # other-tenant excluded
|
||||
model = data["top"][0]
|
||||
self.assertEqual(model["model"], "gpt-x")
|
||||
self.assertEqual(model["requests"], 9)
|
||||
self.assertEqual(model["known_tokens"], 100 + 1000 + 10 + 14 + 14)
|
||||
self.assertEqual(model["value"], 9)
|
||||
dumped = repr(model)
|
||||
self.assertNotIn("tg100", dumped)
|
||||
self.assertNotIn("alice", dumped)
|
||||
for forbidden in ("user", "uid", "token_name", "key"):
|
||||
self.assertNotIn(forbidden, model)
|
||||
|
||||
def test_blank_model_name_reported_as_null(self):
|
||||
make_gw_db(self.gw, [
|
||||
(2, NOW - 10, "tg100", "", 1, 1, 1),
|
||||
(2, NOW - 20, "tg100", None, 1, 1, 1),
|
||||
(2, NOW - 30, "tg100", "real", 1, 1, 1),
|
||||
])
|
||||
models = self.call("models", "week")["top"]
|
||||
self.assertEqual([m["model"] for m in models], [None, "real"])
|
||||
self.assertEqual(sum(m["requests"] for m in models), 3)
|
||||
|
||||
def test_period_windows(self):
|
||||
week = self.call("requests", "week")
|
||||
alice = [r for r in week["top"] if r["user"] == "@alice"][0]
|
||||
self.assertEqual(alice["requests"], 5) # 8d/20d rows excluded
|
||||
month = self.call("requests", "month")
|
||||
alice_m = [r for r in month["top"] if r["user"] == "@alice"][0]
|
||||
self.assertEqual(alice_m["requests"], 7) # 20d row joins, 8d still inside 30d
|
||||
self.assertEqual(month["from_ts"], NOW - 30 * DAY)
|
||||
day = self.call("requests", "day")
|
||||
self.assertEqual((day["from_ts"] + rankings.MSK_OFFSET) % DAY, 0)
|
||||
self.assertLessEqual(day["from_ts"], NOW)
|
||||
alice_day = [r for r in day["top"] if r["user"] == "@alice"]
|
||||
expected = 5 if NOW - 100 >= day["from_ts"] else 0
|
||||
self.assertEqual(alice_day[0]["requests"] if alice_day else 0, expected)
|
||||
|
||||
|
||||
class ParameterTests(Base):
|
||||
def test_kind_period_limit_validation(self):
|
||||
self.assertEqual(rankings.normalize_kind(" TOKENS "), "tokens")
|
||||
for bad in ("", "users", "../x", 1):
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.normalize_kind(bad)
|
||||
self.assertEqual(rankings.normalize_period(None, "referrals"), "all")
|
||||
self.assertEqual(rankings.normalize_period(None, "tokens"), "week")
|
||||
self.assertEqual(rankings.normalize_period("MONTH", "tokens"), "month")
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.normalize_period("all", "requests")
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.normalize_period("year", "referrals")
|
||||
self.assertEqual(rankings.normalize_limit(None), 20)
|
||||
self.assertEqual(rankings.normalize_limit("5"), 5)
|
||||
for bad in (0, 101, "x", True, -1, "2.5"):
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.normalize_limit(bad)
|
||||
|
||||
def test_bad_params_never_touch_database(self):
|
||||
missing = self.dir / "nope.db"
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.top(missing, missing, "nope", "week", now=NOW)
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.top(missing, missing, "tokens", "all", now=NOW)
|
||||
with self.assertRaises(ValueError):
|
||||
rankings.top(missing, missing, "referrals", "week", now=NOW, limit=0)
|
||||
|
||||
def test_envelope_contract(self):
|
||||
make_bot_db(self.bot, [(1, "a", None, None, 0, 0, 0)])
|
||||
data = self.call(period=None)
|
||||
for key in ("top", "kind", "period", "source", "from_ts", "to_ts", "as_of",
|
||||
"limit", "ranked", "truncated", "generated_at", "timezone", "value"):
|
||||
self.assertIn(key, data)
|
||||
self.assertEqual(data["source"], "bot.users.ref_awarded")
|
||||
self.assertEqual(data["timezone"], "Europe/Moscow")
|
||||
self.assertEqual(data["as_of"], data["to_ts"])
|
||||
self.assertEqual(data["limit"], 20)
|
||||
|
||||
def test_limit_and_truncated(self):
|
||||
users = [(i, "u%d" % i, None, None, 0, 0, 0) for i in range(1, 6)]
|
||||
users += [(100 + i, "r%d" % i, i, NOW - 10, 1, 0, 0) for i in range(1, 6)]
|
||||
make_bot_db(self.bot, users)
|
||||
data = self.call(period="week", limit=2)
|
||||
self.assertEqual(len(data["top"]), 2)
|
||||
self.assertEqual([r["pos"] for r in data["top"]], [1, 2])
|
||||
self.assertEqual(data["ranked"], 5)
|
||||
self.assertTrue(data["truncated"])
|
||||
|
||||
|
||||
class ErrorTests(Base):
|
||||
def test_missing_gateway_db_raises_sqlite_error(self):
|
||||
make_bot_db(self.bot, [(100, "alice", None, None, 0, 0, 0)])
|
||||
with self.assertRaises(sqlite3.Error):
|
||||
rankings.top(self.bot, self.dir / "absent.db", "tokens", "week", now=NOW)
|
||||
|
||||
def test_missing_logs_table_raises_sqlite_error(self):
|
||||
make_bot_db(self.bot, [(100, "alice", None, None, 0, 0, 0)])
|
||||
con = sqlite3.connect(self.gw)
|
||||
con.execute("CREATE TABLE unrelated (x INTEGER)")
|
||||
con.commit()
|
||||
con.close()
|
||||
with self.assertRaises(sqlite3.Error):
|
||||
rankings.top(self.bot, self.gw, "requests", "week", now=NOW)
|
||||
|
||||
def test_missing_bot_db_raises_sqlite_error(self):
|
||||
make_gw_db(self.gw, [(2, NOW - 10, "tg100", "m", 1, 1, 1)])
|
||||
with self.assertRaises(sqlite3.Error):
|
||||
rankings.top(self.dir / "absent.db", self.gw, "referrals", "week", now=NOW)
|
||||
|
||||
def test_account_uid_exact_rule(self):
|
||||
self.assertEqual(rankings.account_uid("tg100"), 100)
|
||||
self.assertEqual(rankings.account_uid("pm42-k7"), 42)
|
||||
self.assertEqual(rankings.account_uid("sol9000000000-k1"), 9_000_000_000)
|
||||
for bad in ("tg0100", "tg100-k0", "tg100-k", "xtg100", "tg1009x", "tg",
|
||||
"TG100", "", None, 100):
|
||||
self.assertIsNone(rankings.account_uid(bad), bad)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,576 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const html = readFileSync(new URL('../bot/webapp/static/index.html', import.meta.url), 'utf8');
|
||||
const lines = html.split(/\r?\n/);
|
||||
function declaration(prefix) {
|
||||
const line = lines.find(value => value.startsWith(prefix));
|
||||
assert.ok(line, `Missing application declaration: ${prefix}`);
|
||||
return line;
|
||||
}
|
||||
function between(start, end) {
|
||||
const first = html.indexOf(start);
|
||||
const last = html.indexOf(end, first + start.length);
|
||||
assert.ok(first >= 0 && last > first, `Missing source block: ${start}`);
|
||||
return html.slice(first, last);
|
||||
}
|
||||
const dailySource = between('/* ---------- Ежедневный кубик:', '/* ---------- Квесты и монеты сообщества');
|
||||
const rankingSource = between('/* ---------- Рейтинги:', '/* ---------- Нейролаб:');
|
||||
const questSource = between('function questsView(', 'let questBusy=') + declaration('let questBusy=');
|
||||
const helpers = [
|
||||
'const esc=', 'const num=', 'const fmt=', 'const usd=', 'const refreshBtn=',
|
||||
'const intro=', 'const ECON_PERIODS=', 'const ECON_PERIOD_DETAILS=',
|
||||
'const usageCount=', 'const usageGrouped=',
|
||||
].map(declaration).join('\n');
|
||||
|
||||
function element(dataset = {}) {
|
||||
return {
|
||||
dataset, innerHTML: '', attributes: {}, hidden: false,
|
||||
setAttribute(name, value) { this.attributes[name] = value; },
|
||||
querySelector() { return null; },
|
||||
};
|
||||
}
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
function envelope(kind, rows = [], period = kind === 'referrals' ? 'all' : 'day') {
|
||||
return {
|
||||
kind, period, top: rows,
|
||||
source: kind === 'referrals' ? 'bot.users.ref_awarded' : kind === 'models' ? 'gateway.logs(type=2).model_name' : 'gateway.logs(type=2)',
|
||||
from_ts: kind === 'referrals' ? null : 1700000000,
|
||||
to_ts: 1700086400, as_of: 1700086400, generated_at: 1700086400,
|
||||
timezone: 'Europe/Moscow',
|
||||
};
|
||||
}
|
||||
function dailyStatus(overrides = {}) {
|
||||
return {
|
||||
ok: true, claimed: false, paid: false, pending: false,
|
||||
face: null, value: null, units: null, usd: null,
|
||||
eligible: true, wallet: true, rank: 1, multiplier: 1,
|
||||
streak: 2, day: '2026-10-28', already: false, resumed: false,
|
||||
legacy: false, error: null, ...overrides,
|
||||
};
|
||||
}
|
||||
function harness(overrides = {}) {
|
||||
const roots = {
|
||||
'#top-results': element(), '#top-periods': element(), '#econ-daily': element(),
|
||||
};
|
||||
const kinds = ['referrals', 'requests', 'tokens', 'models'].map(topKind => element({ topKind }));
|
||||
const periods = ['day', 'week', 'month'].map(topPeriod => element({ topPeriod }));
|
||||
const reads = [], writes = [], haptics = [];
|
||||
const context = vm.createContext({
|
||||
current: 'top', version: 1, resolvedUid: 'test-account', cache: new Map(),
|
||||
$: selector => roots[selector] || null,
|
||||
icon: () => '<svg aria-hidden="true"></svg>',
|
||||
haptic: value => haptics.push(value),
|
||||
document: { querySelectorAll: selector => selector === '[data-top-kind]' ? kinds : selector === '[data-top-period]' ? periods : [] },
|
||||
apiFresh: async path => {
|
||||
reads.push(path);
|
||||
if (path === 'bonus') return dailyStatus();
|
||||
const url = new URL(path, 'https://miniapp.test/');
|
||||
return envelope(url.searchParams.get('kind'), [], url.searchParams.get('period'));
|
||||
},
|
||||
post: async (path, body) => { writes.push({ path, body }); throw new Error('Unexpected mutation'); },
|
||||
...overrides,
|
||||
});
|
||||
vm.runInContext(`${helpers}\n${dailySource}\n${rankingSource}\n${questSource}\n` + `
|
||||
globalThis.frontend = {
|
||||
topView, topResults, topMeta, topMetric, topPath, topSelect, topLoad,
|
||||
dailyView, dailyReceive, dailyClaim, dailyRefresh, dailyStatusValid, questsView,
|
||||
getDaily: () => dailyState,
|
||||
setSelection: (kind, period) => { topKind = kind; topPeriod = period; },
|
||||
getSelection: () => ({ kind: topKind, period: topPeriod }),
|
||||
};
|
||||
`, context);
|
||||
return { context, frontend: context.frontend, roots, kinds, periods, reads, writes, haptics };
|
||||
}
|
||||
function claimButton(markup) {
|
||||
return markup.match(/<button\b[^>]*data-daily-claim[^>]*>/)?.[0] || '';
|
||||
}
|
||||
|
||||
test('all inline JavaScript parses without executing the application', () => {
|
||||
const scripts = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)];
|
||||
assert.ok(scripts.length >= 2);
|
||||
for (const [, attributes, source] of scripts) {
|
||||
if (/\bsrc=/.test(attributes)) continue;
|
||||
assert.doesNotThrow(() => new vm.Script(source));
|
||||
}
|
||||
});
|
||||
|
||||
test('four named ranking controls expose selected state and a results relationship', () => {
|
||||
const { frontend } = harness();
|
||||
const markup = frontend.topView(envelope('referrals'), { rich: [], casino: [] });
|
||||
assert.equal((markup.match(/data-top-kind=/g) || []).length, 4);
|
||||
for (const [kind, label] of [['referrals', 'Рефералы'], ['requests', 'Запросы'], ['tokens', 'Токены'], ['models', 'Модели']]) {
|
||||
assert.match(markup, new RegExp(`data-top-kind="${kind}"[^>]*aria-controls="top-results"[^>]*aria-pressed="${kind === 'referrals'}"[^>]*>${label}<`));
|
||||
}
|
||||
assert.match(markup, /aria-label="Вид рейтинга"/);
|
||||
assert.match(markup, /id="top-results"[^>]*aria-live="polite"/);
|
||||
assert.match(markup, /id="top-periods"[^>]* hidden/);
|
||||
assert.match(markup, /За всё время/);
|
||||
});
|
||||
|
||||
test('usage periods are explicit, while referrals always request the lifetime board', () => {
|
||||
const { frontend } = harness();
|
||||
assert.equal(frontend.topPath('referrals', 'month'), 'top?kind=referrals&period=all');
|
||||
assert.equal(frontend.topPath('requests', 'day'), 'top?kind=requests&period=day');
|
||||
assert.equal(frontend.topPath('tokens', 'week'), 'top?kind=tokens&period=week');
|
||||
assert.equal(frontend.topPath('models', 'month'), 'top?kind=models&period=month');
|
||||
frontend.setSelection('requests', 'week');
|
||||
const markup = frontend.topView(envelope('requests', [], 'week'), null);
|
||||
assert.doesNotMatch(markup, /id="top-periods"[^>]* hidden/);
|
||||
assert.match(markup, /data-top-period="day"[^>]*>Сегодня</);
|
||||
assert.match(markup, /data-top-period="week"[^>]*aria-pressed="true"[^>]*>7 дней</);
|
||||
assert.match(markup, /data-top-period="month"[^>]*>30 дней</);
|
||||
assert.match(markup, /Последние 7 дней/);
|
||||
});
|
||||
|
||||
test('each ranking renders its actual metric instead of referral fields or money', () => {
|
||||
const { frontend } = harness();
|
||||
const row = { pos: 1, user: '@member', refs: 2.5, count: 9, requests: 1234, value: 1234, known_tokens: 98765, tokens: 98765, unknown_token_requests: 0, tokens_complete: true };
|
||||
assert.equal(frontend.topMetric(row, 'referrals').value, '2,5');
|
||||
assert.equal(frontend.topMetric(row, 'referrals').detail, '9 приглашено');
|
||||
assert.equal(frontend.topMetric(row, 'requests').value, '1 234');
|
||||
assert.equal(frontend.topMetric(row, 'requests').unit, 'запросов');
|
||||
assert.equal(frontend.topMetric(row, 'tokens').value, '98 765');
|
||||
assert.equal(frontend.topMetric(row, 'tokens').unit, 'токенов');
|
||||
const modelMarkup = frontend.topResults(envelope('models', [{ ...row, model: 'gpt-model', user: '@must-not-be-used' }]), 'models', 'day');
|
||||
assert.match(modelMarkup, />gpt-model</);
|
||||
assert.match(modelMarkup, /1 234<small>запросов</);
|
||||
assert.doesNotMatch(modelMarkup, /@must-not-be-used|2,5<small>|\$|реф\. вес/);
|
||||
const unnamed = frontend.topResults(envelope('models', [{ pos: 1, model: null, requests: 4 }]), 'models', 'day');
|
||||
assert.match(unnamed, /Модель не указана/);
|
||||
});
|
||||
|
||||
test('token rows distinguish lower bounds, entirely unknown counters and exact zero', () => {
|
||||
const { frontend } = harness();
|
||||
const lower = { pos: 1, user: '@lower', known_tokens: 4500, tokens: null, unknown_token_requests: 3, tokens_complete: false };
|
||||
const metric = frontend.topMetric(lower, 'tokens');
|
||||
assert.equal(metric.value, '≥ 4 500');
|
||||
assert.match(metric.unit, /нижняя граница/);
|
||||
assert.match(metric.detail, /3$/);
|
||||
const unknown = frontend.topMetric({ known_tokens: 0, tokens: null, unknown_token_requests: 7, tokens_complete: false }, 'tokens');
|
||||
assert.equal(unknown.value, 'Неизвестно');
|
||||
assert.notEqual(unknown.value, '0');
|
||||
assert.equal(frontend.topMetric({ known_tokens: 0, tokens: 0, unknown_token_requests: 0, tokens_complete: true }, 'tokens').value, '0');
|
||||
const markup = frontend.topResults(envelope('tokens', [lower]), 'tokens', 'day');
|
||||
assert.match(markup, /Входные \+ выходные токены/);
|
||||
assert.match(markup, /Запросов без полного счётчика: 3/);
|
||||
assert.match(markup, /без пересчёта по цене модели/);
|
||||
});
|
||||
|
||||
test('missing or invalid metrics are never fabricated as zero', () => {
|
||||
const { frontend } = harness();
|
||||
assert.equal(frontend.topMetric({}, 'requests').value, '—');
|
||||
assert.equal(frontend.topMetric({ requests: -1 }, 'models').value, '—');
|
||||
assert.equal(frontend.topMetric({ tokens: '0', known_tokens: null }, 'tokens').value, 'Неизвестно');
|
||||
assert.equal(frontend.topMetric({ refs: null, count: undefined }, 'referrals').value, '—');
|
||||
});
|
||||
|
||||
test('source and Moscow boundaries are visible, and missing boundaries are acknowledged', () => {
|
||||
const { frontend } = harness();
|
||||
const markup = frontend.topMeta(envelope('requests'), 'requests', 'day');
|
||||
assert.match(markup, /Сегодня с 00:00 МСК/);
|
||||
assert.match(markup, /Источник: сохранённая история запросов шлюза/);
|
||||
assert.match(markup, /срез .* МСК/);
|
||||
assert.match(markup, / — .* МСК/);
|
||||
assert.match(frontend.topMeta({ source: 'gateway.logs(type=2)' }, 'requests', 'month'), /точные границы не переданы/);
|
||||
assert.match(frontend.topMeta(envelope('referrals'), 'referrals', 'day'), /зачтённые приглашения в боте/);
|
||||
});
|
||||
|
||||
test('valid empty, malformed and unavailable ranking states are distinct and retryable', () => {
|
||||
const { frontend } = harness();
|
||||
assert.match(frontend.topResults(envelope('requests'), 'requests', 'day'), /За этот период пока нет участников/);
|
||||
for (const invalid of [{}, { top: null }, { top: [null] }, envelope('tokens', [], 'week')]) {
|
||||
const markup = frontend.topResults(invalid, 'requests', 'day');
|
||||
assert.match(markup, /Рейтинг временно недоступен/);
|
||||
assert.match(markup, /data-top-retry/);
|
||||
assert.doesNotMatch(markup, /За этот период пока нет участников/);
|
||||
}
|
||||
const failed = frontend.topResults(null, 'tokens', 'day', { status: 503 });
|
||||
assert.match(failed, /HTTP 503/);
|
||||
assert.match(failed, /не означает нулевую активность/);
|
||||
assert.doesNotMatch(failed, /пока нет участников/);
|
||||
});
|
||||
|
||||
test('legacy balance and weekly boards remain, with honest source failure instead of disappearance', () => {
|
||||
const { frontend } = harness();
|
||||
const boards = { rich: [{ pos: 1, user: '@rich', usd: 12 }], casino: [{ pos: 1, user: '@oldboard', n: 2 }] };
|
||||
const markup = frontend.topView(envelope('referrals'), boards);
|
||||
assert.match(markup, /Топ балансов/);
|
||||
assert.match(markup, /@rich/);
|
||||
assert.match(markup, /Рискующие недели/);
|
||||
assert.match(markup, /@oldboard/);
|
||||
const failed = frontend.topView(envelope('referrals'), null, null, { status: 503 });
|
||||
assert.match(failed, /Другие рейтинги временно недоступны/);
|
||||
assert.doesNotMatch(failed, /Пока пусто/);
|
||||
});
|
||||
|
||||
test('ranking names, model IDs, sources and legacy board names are HTML-escaped', () => {
|
||||
const { frontend } = harness();
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const payload = envelope('requests', [{ pos: 1, user: attack, requests: 1 }]);
|
||||
payload.source = '<script>alert(1)</script>';
|
||||
const markup = frontend.topResults(payload, 'requests', 'day');
|
||||
assert.doesNotMatch(markup, /<img|<script>/);
|
||||
assert.match(markup, /<img src=x onerror="alert\(1\)">/);
|
||||
assert.match(markup, /<script>/);
|
||||
const model = frontend.topResults(envelope('models', [{ pos: 1, model: attack, requests: 1 }]), 'models', 'day');
|
||||
assert.doesNotMatch(model, /<img/);
|
||||
const board = frontend.topView(envelope('referrals'), { rich: [{ pos: 1, user: attack, usd: 1 }] });
|
||||
assert.doesNotMatch(board, /<img/);
|
||||
});
|
||||
|
||||
test('switching updates accessible controls, rejects invalid selections and preserves the chosen period', async () => {
|
||||
const { frontend, roots, kinds, periods, reads } = harness();
|
||||
assert.equal(frontend.topSelect('requests', 'month'), true);
|
||||
assert.equal(roots['#top-periods'].hidden, false);
|
||||
assert.equal(kinds.find(button => button.dataset.topKind === 'requests').attributes['aria-pressed'], 'true');
|
||||
assert.equal(periods.find(button => button.dataset.topPeriod === 'month').attributes['aria-pressed'], 'true');
|
||||
assert.equal(frontend.topSelect('requests', 'month'), false);
|
||||
assert.equal(frontend.topSelect('unknown', 'month'), false);
|
||||
assert.equal(frontend.topSelect('tokens', 'year'), false);
|
||||
await Promise.resolve();
|
||||
assert.deepEqual(reads, ['top?kind=requests&period=month']);
|
||||
assert.equal(frontend.topSelect('referrals', 'month'), true);
|
||||
assert.equal(roots['#top-periods'].hidden, true);
|
||||
await Promise.resolve();
|
||||
assert.equal(reads.at(-1), 'top?kind=referrals&period=all');
|
||||
assert.equal(frontend.getSelection().period, 'month');
|
||||
});
|
||||
|
||||
test('an older request cannot clear a newer loading state or populate another ranking', async () => {
|
||||
const first = deferred(), second = deferred(), calls = [];
|
||||
const { frontend, roots } = harness({ apiFresh: path => { calls.push(path); return calls.length === 1 ? first.promise : second.promise; } });
|
||||
frontend.setSelection('requests', 'day');
|
||||
const oldLoad = frontend.topLoad();
|
||||
frontend.setSelection('tokens', 'week');
|
||||
const newLoad = frontend.topLoad();
|
||||
first.resolve(envelope('requests', [{ pos: 1, user: '@old', requests: 100 }]));
|
||||
await oldLoad;
|
||||
assert.equal(roots['#top-results'].attributes['aria-busy'], 'true');
|
||||
assert.match(roots['#top-results'].innerHTML, /Загружаю рейтинг/);
|
||||
second.resolve(envelope('tokens', [{ pos: 1, user: '@new', known_tokens: 8, tokens: 8, unknown_token_requests: 0, tokens_complete: true }], 'week'));
|
||||
await newLoad;
|
||||
assert.equal(roots['#top-results'].attributes['aria-busy'], 'false');
|
||||
assert.match(roots['#top-results'].innerHTML, /@new/);
|
||||
assert.doesNotMatch(roots['#top-results'].innerHTML, /@old/);
|
||||
assert.deepEqual(calls, ['top?kind=requests&period=day', 'top?kind=tokens&period=week']);
|
||||
});
|
||||
|
||||
test('late ranking failures cannot overwrite a newer result', async () => {
|
||||
const first = deferred(), second = deferred();
|
||||
let count = 0;
|
||||
const { frontend, roots } = harness({ apiFresh: () => ++count === 1 ? first.promise : second.promise });
|
||||
frontend.setSelection('requests', 'day');
|
||||
const a = frontend.topLoad();
|
||||
frontend.setSelection('models', 'month');
|
||||
const b = frontend.topLoad();
|
||||
second.resolve(envelope('models', [{ pos: 1, model: 'latest-model', requests: 12 }], 'month'));
|
||||
await b;
|
||||
first.reject({ status: 503 });
|
||||
await a;
|
||||
assert.match(roots['#top-results'].innerHTML, /latest-model/);
|
||||
assert.doesNotMatch(roots['#top-results'].innerHTML, /временно недоступен/);
|
||||
});
|
||||
|
||||
test('ranking failures are shown and a fresh retry can recover without showing zeros', async () => {
|
||||
let count = 0;
|
||||
const { frontend, roots } = harness({ apiFresh: async () => {
|
||||
if (++count === 1) throw { status: 503 };
|
||||
return envelope('requests', [{ pos: 1, user: '@recovered', requests: 17 }]);
|
||||
} });
|
||||
frontend.setSelection('requests', 'day');
|
||||
await frontend.topLoad();
|
||||
assert.match(roots['#top-results'].innerHTML, /HTTP 503/);
|
||||
assert.match(roots['#top-results'].innerHTML, /data-top-retry/);
|
||||
assert.equal(roots['#top-results'].attributes['aria-busy'], 'false');
|
||||
await frontend.topLoad();
|
||||
assert.match(roots['#top-results'].innerHTML, /@recovered/);
|
||||
assert.doesNotMatch(roots['#top-results'].innerHTML, /временно недоступен/);
|
||||
assert.equal(count, 2);
|
||||
});
|
||||
|
||||
test('in-flight ranking data does not cross an account or screen-version boundary', async () => {
|
||||
for (const changed of ['account', 'version']) {
|
||||
const request = deferred();
|
||||
const { frontend, roots, context } = harness({ apiFresh: () => request.promise });
|
||||
frontend.setSelection('requests', 'day');
|
||||
const load = frontend.topLoad();
|
||||
if (changed === 'account') context.resolvedUid = 'other-account';
|
||||
else context.version++;
|
||||
roots['#top-results'].innerHTML = 'new screen';
|
||||
request.resolve(envelope('requests', [{ pos: 1, user: '@old-account', requests: 100 }]));
|
||||
await load;
|
||||
assert.equal(roots['#top-results'].innerHTML, 'new screen');
|
||||
}
|
||||
});
|
||||
|
||||
test('daily ready, busy and paid states have explicit actionable controls', () => {
|
||||
const { frontend } = harness();
|
||||
const ready = frontend.dailyView({ data: dailyStatus() });
|
||||
assert.match(ready, /Ежедневный кубик и чек-ин/);
|
||||
assert.match(ready, /Бросить кубик и отметить день/);
|
||||
assert.doesNotMatch(claimButton(ready), /disabled/);
|
||||
assert.match(ready, /00:00 МСК/);
|
||||
assert.match(ready, /не деньги к выводу/);
|
||||
assert.doesNotMatch(ready, /Результат кубика: [1-6]/);
|
||||
const busy = frontend.dailyView({ data: dailyStatus(), busy: true });
|
||||
assert.match(busy, /aria-busy="true"/);
|
||||
assert.match(claimButton(busy), /disabled aria-disabled="true"/);
|
||||
assert.match(busy, /data-daily-refresh[^>]*disabled/);
|
||||
const paid = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: true, face: 6, value: 6, units: 20000000, usd: 40, already: true }) });
|
||||
assert.match(paid, /Результат кубика: 6 из 6/);
|
||||
assert.equal((paid.match(/daily-pip on/g) || []).length, 6);
|
||||
assert.match(paid, /40 \$ API-кредита/);
|
||||
assert.match(paid, /Сегодня уже отмечено/);
|
||||
assert.match(paid, /Начисление подтверждено/);
|
||||
assert.match(claimButton(paid), /disabled/);
|
||||
});
|
||||
|
||||
test('daily face is not inferred from units or value, and legacy rewards never become fictional zero', () => {
|
||||
const { frontend } = harness();
|
||||
const legacy = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: true, already: true, legacy: true, face: null, value: 6, units: null, usd: null }) });
|
||||
assert.doesNotMatch(legacy, /Результат кубика: 6|0 \$ API-кредита/);
|
||||
assert.match(legacy, /Размер награды не передан сервером/);
|
||||
assert.match(claimButton(legacy), /disabled/);
|
||||
});
|
||||
|
||||
test('legacy check-in marker is not a paid reward or a recoverable roll', async () => {
|
||||
const { frontend, context, writes } = harness();
|
||||
context.current = 'econ';
|
||||
const data = dailyStatus({ legacy: true, claimed: true, paid: false, pending: false, already: true, face: null, units: null, usd: null });
|
||||
const state = frontend.dailyReceive(data);
|
||||
for (const uncertain of [false, true]) {
|
||||
state.uncertain = uncertain;
|
||||
const markup = frontend.dailyView(state);
|
||||
assert.match(markup, /Сегодняшний чек-ин уже отмечен в прежней версии\. Новый кубик — завтра\./);
|
||||
assert.match(claimButton(markup), /disabled aria-disabled="true"/);
|
||||
assert.doesNotMatch(markup, /Начисление подтверждено|Награда за сегодня:|Награда по сохранённому результату:|Проверить начисление|Результат кубика: [1-6]/);
|
||||
await frontend.dailyClaim();
|
||||
}
|
||||
assert.equal(writes.length, 0);
|
||||
assert.equal(frontend.getDaily().data.paid, false);
|
||||
});
|
||||
|
||||
test('legacy result discovered by POST is closed without claiming payout or permitting another roll', async () => {
|
||||
let calls = 0;
|
||||
const { frontend, context, roots } = harness({ post: async () => {
|
||||
calls++;
|
||||
return dailyStatus({ legacy: true, claimed: true, paid: false, pending: false, already: true });
|
||||
} });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(frontend.getDaily().data.paid, false);
|
||||
assert.equal(frontend.getDaily().uncertain, false);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /Новый кубик — завтра/);
|
||||
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено|Начисление не подтверждено/);
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('pending daily recovery keeps the real face and reward but does not claim credit was paid', () => {
|
||||
const { frontend } = harness();
|
||||
const markup = frontend.dailyView({ data: dailyStatus({ claimed: true, paid: false, pending: true, face: 5, value: 5, usd: 30 }) });
|
||||
assert.match(markup, /Результат кубика: 5 из 6/);
|
||||
assert.match(markup, /30 \$ API-кредита/);
|
||||
assert.match(markup, /Начисление не подтверждено/);
|
||||
assert.match(markup, /Проверить начисление/);
|
||||
assert.doesNotMatch(claimButton(markup), /disabled/);
|
||||
assert.doesNotMatch(markup, /Начисление подтверждено|Награда за сегодня:/);
|
||||
});
|
||||
|
||||
test('failed status payload can still expose an idempotent pending recovery', () => {
|
||||
const { frontend, context } = harness();
|
||||
context.current = 'econ';
|
||||
const data = dailyStatus({ ok: false, claimed: true, pending: true, paid: false, face: 2, usd: 16, error: 'daily_failed' });
|
||||
const state = frontend.dailyReceive(undefined, { status: 503, data });
|
||||
const markup = frontend.dailyView(state);
|
||||
assert.equal(state.uncertain, true);
|
||||
assert.match(markup, /Результат кубика: 2 из 6/);
|
||||
assert.match(markup, /HTTP 503/);
|
||||
assert.doesNotMatch(claimButton(markup), /disabled/);
|
||||
assert.doesNotMatch(markup, /Начисление подтверждено/);
|
||||
});
|
||||
|
||||
test('daily double-click sends one POST {}, and paid or already responses prevent another request', async () => {
|
||||
const request = deferred(), writes = [];
|
||||
const { frontend, context, roots } = harness({ post: (path, body) => { writes.push({ path, body }); return request.promise; } });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
const first = frontend.dailyClaim();
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(writes.length, 1);
|
||||
assert.equal(writes[0].path, 'daily');
|
||||
assert.equal(JSON.stringify(writes[0].body), '{}');
|
||||
assert.equal(frontend.getDaily().busy, true);
|
||||
assert.match(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
|
||||
request.resolve(dailyStatus({ claimed: true, paid: true, face: 3, value: 3, units: 10000000, usd: 20, credited_units: 0, already: true }));
|
||||
await first;
|
||||
assert.equal(frontend.getDaily().busy, false);
|
||||
assert.equal(frontend.getDaily().data.paid, true);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /20 \$ API-кредита/);
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(writes.length, 1);
|
||||
});
|
||||
|
||||
test('503 daily response preserves pending face; retry uses the same endpoint and never rerolls locally', async () => {
|
||||
const writes = [];
|
||||
const pending = dailyStatus({ ok: false, claimed: true, paid: false, pending: true, face: 4, usd: 24, units: 12000000, error: 'daily_failed' });
|
||||
const { frontend, context, roots } = harness({ post: async (path, body) => {
|
||||
writes.push({ path, body });
|
||||
if (writes.length === 1) throw { status: 503, requestSent: true, data: pending };
|
||||
return { ...pending, ok: true, paid: true, pending: false, already: true, resumed: true, credited_units: 0, error: null };
|
||||
} });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(frontend.getDaily().uncertain, true);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /Результат кубика: 4 из 6/);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /24 \$ API-кредита/);
|
||||
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено/);
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(writes.length, 2);
|
||||
assert.equal(writes[1].path, 'daily');
|
||||
assert.equal(JSON.stringify(writes[1].body), '{}');
|
||||
assert.equal(frontend.getDaily().data.face, 4);
|
||||
assert.equal(frontend.getDaily().data.usd, 24);
|
||||
assert.equal(frontend.getDaily().data.paid, true);
|
||||
assert.doesNotMatch(dailySource, /Math\.random|post\(['"](?:spin|task)/);
|
||||
});
|
||||
|
||||
test('network failure or incomplete success never becomes a paid daily claim and remains retryable', async () => {
|
||||
for (const result of ['network', 'incomplete']) {
|
||||
const { frontend, context, roots } = harness({ post: async () => {
|
||||
if (result === 'network') throw new Error('connection lost');
|
||||
return { ok: true, face: 6, usd: 40 };
|
||||
} });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(frontend.getDaily().data.paid, false);
|
||||
assert.equal(frontend.getDaily().uncertain, true);
|
||||
assert.doesNotMatch(roots['#econ-daily'].innerHTML, /Начисление подтверждено/);
|
||||
assert.doesNotMatch(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /Проверить начисление/);
|
||||
}
|
||||
});
|
||||
|
||||
test('wallet rejection explains API-key recovery; a fresh status makes the action usable again', async () => {
|
||||
const { frontend, context, roots, reads } = harness({ post: async () => {
|
||||
throw { status: 409, data: dailyStatus({ ok: false, wallet: false, error: 'daily_wallet' }) };
|
||||
} });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(frontend.getDaily().uncertain, false);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /Основной API-ключ недоступен/);
|
||||
assert.match(roots['#econ-daily'].innerHTML, /data-tab="keys"/);
|
||||
assert.match(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
|
||||
await frontend.dailyRefresh();
|
||||
assert.equal(reads.at(-1), 'bonus');
|
||||
assert.doesNotMatch(claimButton(roots['#econ-daily'].innerHTML), /disabled/);
|
||||
});
|
||||
|
||||
test('late daily response cannot cross an account boundary', async () => {
|
||||
const request = deferred();
|
||||
const { frontend, context } = harness({ post: () => request.promise });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
const claim = frontend.dailyClaim();
|
||||
context.resolvedUid = 'another-account';
|
||||
frontend.dailyReceive(dailyStatus({ streak: 0 }));
|
||||
request.resolve(dailyStatus({ claimed: true, paid: true, face: 6, usd: 40 }));
|
||||
await claim;
|
||||
assert.equal(frontend.getDaily().uid, 'another-account');
|
||||
assert.equal(frontend.getDaily().data.paid, false);
|
||||
assert.equal(frontend.getDaily().data.face, null);
|
||||
});
|
||||
|
||||
test('daily error and untrusted scalar fields cannot insert HTML', () => {
|
||||
const { frontend } = harness();
|
||||
const attack = '<img src=x onerror="alert(1)">';
|
||||
const markup = frontend.dailyView({ data: dailyStatus({ face: attack, usd: attack, streak: attack, day: attack }), error: { status: attack } });
|
||||
assert.doesNotMatch(markup, /<img/);
|
||||
assert.match(markup, /<img/);
|
||||
assert.doesNotMatch(markup, /Результат кубика: <|Награда за сегодня:/);
|
||||
});
|
||||
|
||||
test('quest check-in remains callable and pending recovery is not disabled', () => {
|
||||
const { frontend } = harness();
|
||||
const base = { rank_name: 'Новичок', budget_left_usd: 2, budget_usd: 3, quests: [{ id: 'checkin', title: 'Дневной чек-ин', target: 1, progress: 0, reward_usd: 1, claimable: true, done: false }] };
|
||||
const markup = frontend.questsView(base, false);
|
||||
assert.match(markup, /data-quest="checkin"[^>]*>Чек-ин и получить/);
|
||||
assert.match(markup, /API-кредита/);
|
||||
assert.match(markup, /Чек-ин доступен здесь/);
|
||||
const pending = frontend.questsView({ ...base, quests: [{ ...base.quests[0], claimable: false, pending: true }] }, false);
|
||||
assert.match(pending, /data-quest="checkin"[^>]*>Проверить начисление/);
|
||||
assert.doesNotMatch(pending.match(/<button\b[^>]*data-quest="checkin"[^>]*>/)?.[0] || '', /disabled/);
|
||||
});
|
||||
|
||||
test('rankings and daily are wired to route rendering and delegated click actions', () => {
|
||||
assert.match(html, /settled\(topPath\(\)\)/);
|
||||
assert.match(html, /settled\('bonus'\)/);
|
||||
assert.match(html, /id="econ-daily"/);
|
||||
assert.match(html, /\[data-top-kind\][\s\S]*topSelect\(topKindButton\.dataset\.topKind\)/);
|
||||
assert.match(html, /\[data-top-retry\][\s\S]*topLoad\(\)/);
|
||||
assert.match(html, /\[data-daily-claim\][\s\S]*dailyClaim\(\)/);
|
||||
assert.match(html, /\[data-daily-refresh\][\s\S]*dailyRefresh\(\)/);
|
||||
});
|
||||
|
||||
test('new compact controls compose existing tokens, minimum tap targets and focus styles', () => {
|
||||
const styles = html.match(/<style>([\s\S]*?)<\/style>/)?.[1] || '';
|
||||
assert.match(styles, /\.top-kinds\{display:grid;grid-template-columns:repeat\(2,minmax\(0,1fr\)\);gap:var\(--space-2\)/);
|
||||
assert.match(styles, /\.econ-periods\[hidden\]\{display:none\}/);
|
||||
assert.match(styles, /\.chipbtn\{min-height:var\(--tap\)/);
|
||||
assert.match(styles, /:focus-visible\{outline:var\(--stroke-strong\) solid var\(--accent\)/);
|
||||
for (const rule of styles.matchAll(/\.(?:top-kinds|top-meta|top-results|daily-card|daily-outcome|daily-face|daily-pip)[^{]*\{([^}]*)\}/g)) {
|
||||
assert.doesNotMatch(rule[1], /#[0-9a-fA-F]{3,8}\b|\b\d+px\b/);
|
||||
}
|
||||
});
|
||||
|
||||
test('confirmed receipt survives failed status reads and incomplete refresh responses', async () => {
|
||||
for (const mode of ['receive', 'refresh']) {
|
||||
const { frontend, context } = harness({ apiFresh: async () => { throw { status: 503 }; } });
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus({ claimed: true, paid: true, face: 6, usd: 40 }));
|
||||
if (mode === 'receive') frontend.dailyReceive(undefined, { status: 503 });
|
||||
else await frontend.dailyRefresh();
|
||||
const state = frontend.getDaily();
|
||||
assert.equal(state.data.paid, true);
|
||||
assert.equal(state.data.face, 6);
|
||||
assert.equal(state.uncertain, false);
|
||||
const markup = frontend.dailyView(state);
|
||||
assert.match(markup, /Начисление подтверждено/);
|
||||
assert.match(claimButton(markup), /disabled/);
|
||||
assert.doesNotMatch(markup, /Начисление не подтверждено|начисление не подтверждено/);
|
||||
}
|
||||
});
|
||||
|
||||
test('authoritative paid receipt in an error body closes claim without a recovery loop', async () => {
|
||||
const receipt = dailyStatus({ claimed: true, paid: true, already: true, face: 4, usd: 24 });
|
||||
for (const mode of ['receive', 'refresh', 'claim']) {
|
||||
let calls = 0;
|
||||
const failure = { status: 409, data: receipt };
|
||||
const { frontend, context } = harness({
|
||||
apiFresh: async () => { throw failure; },
|
||||
post: async () => { calls++; throw failure; },
|
||||
});
|
||||
context.current = 'econ';
|
||||
frontend.dailyReceive(dailyStatus());
|
||||
if (mode === 'receive') frontend.dailyReceive(undefined, failure);
|
||||
else if (mode === 'refresh') await frontend.dailyRefresh();
|
||||
else await frontend.dailyClaim();
|
||||
const state = frontend.getDaily();
|
||||
assert.equal(state.data.paid, true);
|
||||
assert.equal(state.uncertain, false);
|
||||
assert.match(claimButton(frontend.dailyView(state)), /disabled/);
|
||||
await frontend.dailyClaim();
|
||||
assert.equal(calls, mode === 'claim' ? 1 : 0);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Exercise real aiogram registration without importing the side-effectful bot.
|
||||
|
||||
IISHKO_NAV_BOT_SOURCE selects exact deployment bytes for RED/GREEN checks.
|
||||
All users and databases below are synthetic; no Telegram requests are made.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import html
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
import urllib.parse
|
||||
|
||||
from aiogram import F, Router
|
||||
from aiogram.dispatcher.event.bases import UNHANDLED
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
||||
import pytest
|
||||
|
||||
|
||||
SOURCE = Path(os.environ.get(
|
||||
"IISHKO_NAV_BOT_SOURCE",
|
||||
str(Path(__file__).resolve().parents[1] / "bot" / "grok_bot.py"),
|
||||
))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def nav(tmp_path):
|
||||
tree = ast.parse(SOURCE.read_bytes())
|
||||
selected = []
|
||||
names = {"main_kb", "cb_ref", "cb_ref_list", "cmd_effort"}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign) and any(
|
||||
isinstance(target, ast.Name) and target.id == "BTN"
|
||||
for target in node.targets
|
||||
):
|
||||
selected.append(node)
|
||||
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
|
||||
# Keep decorators: stripping them hid the production routing regression.
|
||||
selected.append(node)
|
||||
router = Router()
|
||||
rendered = AsyncMock()
|
||||
db = tmp_path / "referrals.sqlite"
|
||||
with sqlite3.connect(db) as con:
|
||||
con.execute("CREATE TABLE users (tg_id INTEGER PRIMARY KEY, username TEXT, "
|
||||
"token_name TEXT, ref_time INTEGER, ref_awarded INTEGER, referred_by INTEGER)")
|
||||
con.executemany("INSERT INTO users VALUES (?,?,?,?,?,?)", [
|
||||
(100 + i, "friend_%02d" % i if i else "<friend&0>", "", int(time.time()) - 60, i % 2, 42)
|
||||
for i in range(12)
|
||||
] + [(999, "not_your_referral", "", int(time.time()), 1, 77)])
|
||||
ns = {
|
||||
"router": router, "F": F, "Command": Command,
|
||||
"CallbackQuery": SimpleNamespace, "Message": SimpleNamespace,
|
||||
"InlineKeyboardButton": InlineKeyboardButton,
|
||||
"InlineKeyboardMarkup": InlineKeyboardMarkup, "WebAppInfo": WebAppInfo,
|
||||
"WEBAPP_URL": "https://example.com/webapp/", "L": lambda lang, key: key,
|
||||
"db_get": lambda uid: {"lang": "ru"}, "sqlite3": sqlite3,
|
||||
"BOT_DB": str(db), "GW_DB": str(tmp_path / "unused.sqlite"),
|
||||
"time": time, "html": html, "asyncio": asyncio,
|
||||
"tge": lambda glyph: glyph, "rich_page_s": rendered,
|
||||
"page_html": lambda lang, body, rows: "\n".join(body + rows),
|
||||
"account_key_status": SimpleNamespace(UNAVAILABLE="unavailable"),
|
||||
}
|
||||
exec(compile(ast.Module(body=selected, type_ignores=[]), str(SOURCE), "exec"), ns)
|
||||
return SimpleNamespace(router=router, rendered=rendered, ns=ns, db=db)
|
||||
|
||||
|
||||
def callback(data, owner=42):
|
||||
return SimpleNamespace(
|
||||
data=data, from_user=SimpleNamespace(id=owner), bot=object(),
|
||||
message=SimpleNamespace(chat=SimpleNamespace(id=owner, type="private")),
|
||||
answer=AsyncMock(),
|
||||
)
|
||||
|
||||
|
||||
def dispatch(nav, query):
|
||||
return asyncio.run(nav.router.callback_query.trigger(query))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", ["ru", "en"])
|
||||
def test_referrals_are_a_single_full_width_main_menu_entry(nav, lang):
|
||||
kb = nav.ns["main_kb"](lang)
|
||||
rows = [row for row in kb.inline_keyboard if any(b.callback_data == "ref" for b in row)]
|
||||
assert len(rows) == 1
|
||||
assert len(rows[0]) == 1
|
||||
assert rows[0][0].text == ("👥 Referrals" if lang == "en" else "👥 Рефералка")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", ["ru", "en"])
|
||||
def test_main_menu_has_no_settings_button(nav, lang):
|
||||
kb = nav.ns["main_kb"](lang)
|
||||
callbacks = {b.callback_data for row in kb.inline_keyboard for b in row}
|
||||
assert "settings" not in callbacks
|
||||
assert {"ref", "support", "profile", "key", "models"} <= callbacks
|
||||
|
||||
|
||||
def test_effort_command_still_registered(nav):
|
||||
assert any(h.callback is nav.ns["cmd_effort"] for h in nav.router.message.handlers)
|
||||
node = next(n for n in ast.parse(SOURCE.read_bytes()).body
|
||||
if isinstance(n, ast.AsyncFunctionDef) and n.name == "cmd_effort")
|
||||
assert "effort" in ast.unparse(node.decorator_list[0])
|
||||
|
||||
|
||||
def test_referral_page_offers_all_invited(nav):
|
||||
node = next(n for n in ast.parse(SOURCE.read_bytes()).body
|
||||
if isinstance(n, ast.AsyncFunctionDef) and n.name == "cb_ref")
|
||||
assert "ref_list:0" in ast.get_source_segment(SOURCE.read_text(encoding="utf-8"), node)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lang", ["ru", "en"])
|
||||
def test_main_menu_referral_entry_dispatches_to_invited_list(nav, lang):
|
||||
nav.ns.update({
|
||||
"db_get": lambda uid: {"lang": lang},
|
||||
"urllib": urllib, "TOPREF_PRIZES": (3, 2, 1),
|
||||
"refs_weighted": lambda uid: 0,
|
||||
"econ_guard": SimpleNamespace(REF_INVITER_UNITS=500_000, REF_INVITEE_UNITS=500_000),
|
||||
"rank_rules_line": lambda level: "Synthetic rank rule",
|
||||
"back_row": lambda language: '<tg-button data="menu">Back</tg-button>',
|
||||
})
|
||||
menu = nav.ns["main_kb"](lang)
|
||||
entry = next(button for row in menu.inline_keyboard for button in row
|
||||
if button.callback_data == "ref")
|
||||
query = callback(entry.callback_data)
|
||||
assert dispatch(nav, query) is not UNHANDLED
|
||||
nav.rendered.assert_awaited_once()
|
||||
query.answer.assert_awaited_once()
|
||||
assert 'data="ref_list:0"' in nav.rendered.await_args.args[2]
|
||||
assert nav.rendered.await_args.args[3] == 42
|
||||
nav.rendered.reset_mock()
|
||||
listing = callback("ref_list:0")
|
||||
assert dispatch(nav, listing) is not UNHANDLED
|
||||
nav.rendered.assert_awaited_once()
|
||||
listing.answer.assert_awaited_once()
|
||||
assert "not_your_referral" not in nav.rendered.await_args.args[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data, expected_page, count", [
|
||||
("ref_list:0", "1/2", 10),
|
||||
("ref_list:1", "2/2", 2),
|
||||
("ref_list:999999999", "2/2", 2),
|
||||
])
|
||||
def test_registered_callback_lists_only_callers_referrals(nav, data, expected_page, count):
|
||||
query = callback(data)
|
||||
assert dispatch(nav, query) is not UNHANDLED
|
||||
nav.rendered.assert_awaited_once()
|
||||
query.answer.assert_awaited_once()
|
||||
text = nav.rendered.await_args.args[2]
|
||||
assert "Всего: <b>12</b>" in text
|
||||
assert "<b>" + expected_page + "</b>" in text
|
||||
assert text.count("<code>") == count
|
||||
assert "not_your_referral" not in text
|
||||
assert nav.rendered.await_args.args[3] == 42
|
||||
if expected_page == "1/2":
|
||||
assert "ref_list:1" in text
|
||||
else:
|
||||
assert "ref_list:0" in text
|
||||
assert "<friend&0>" in text
|
||||
assert "<friend&0>" not in text
|
||||
|
||||
|
||||
def test_empty_referral_page_is_actionable(nav):
|
||||
query = callback("ref_list:0", owner=88)
|
||||
assert dispatch(nav, query) is not UNHANDLED
|
||||
text = nav.rendered.await_args.args[2]
|
||||
assert "Всего: <b>0</b>" in text
|
||||
assert "Приглашённых пока нет" in text
|
||||
assert 'data="ref"' in text
|
||||
query.answer.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("suffix", ["", "-1", "1:77", "1e3", "١", "1234567890"])
|
||||
def test_malformed_page_never_reads_or_renders_another_users_data(nav, suffix):
|
||||
query = callback("ref_list:" + suffix)
|
||||
assert dispatch(nav, query) is not UNHANDLED
|
||||
nav.rendered.assert_not_awaited()
|
||||
query.answer.assert_awaited_once()
|
||||
|
||||
|
||||
def test_unrelated_callback_not_claimed(nav):
|
||||
query = callback("ref_list_other:0")
|
||||
assert dispatch(nav, query) is UNHANDLED
|
||||
nav.rendered.assert_not_awaited()
|
||||
query.answer.assert_not_awaited()
|
||||
|
||||
|
||||
def test_listing_does_not_mutate_referrals(nav):
|
||||
with sqlite3.connect(nav.db) as con:
|
||||
before = con.execute("SELECT * FROM users ORDER BY tg_id").fetchall()
|
||||
dispatch(nav, callback("ref_list:0"))
|
||||
nav.rendered.assert_awaited_once()
|
||||
with sqlite3.connect(nav.db) as con:
|
||||
after = con.execute("SELECT * FROM users ORDER BY tg_id").fetchall()
|
||||
assert before == after
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Run against actual gateway snapshot via IISHKO_SNAPSHOT_ROOT; no external network."""
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
ROOT = Path(os.environ.get('IISHKO_SNAPSHOT_ROOT', str(Path(__file__).resolve().parents[1] / 'gateway')))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
spec = importlib.util.spec_from_file_location('errorfix_relay', ROOT / 'transparent_api.py')
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError('Cannot load relay from the required snapshot')
|
||||
relay = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(relay)
|
||||
|
||||
|
||||
class InterruptedStreamTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def exercise(self, parts, *, path='/v1/chat/completions', abort=False, timeout=False):
|
||||
calls = []
|
||||
release = asyncio.Event()
|
||||
|
||||
async def upstream(request):
|
||||
calls.append(await request.read())
|
||||
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
for part in parts:
|
||||
await response.write(part)
|
||||
if abort:
|
||||
request.transport.close()
|
||||
elif timeout:
|
||||
await release.wait()
|
||||
else:
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
upstream_app = web.Application()
|
||||
upstream_app.router.add_post(path, upstream)
|
||||
server = TestServer(upstream_app)
|
||||
await server.start_server()
|
||||
session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5, sock_read=3))
|
||||
|
||||
async def proxy(request):
|
||||
async with session.post(server.make_url(path), data=await request.read()) as response:
|
||||
if timeout:
|
||||
# Inject after actual headers/content, not during Windows
|
||||
# connection scheduling; assertions remain identical.
|
||||
class TimedContent:
|
||||
async def iter_chunked(self, size):
|
||||
yield await response.content.readexactly(sum(map(len, parts)))
|
||||
raise asyncio.TimeoutError()
|
||||
response_for_relay = SimpleNamespace(
|
||||
status=response.status, reason=response.reason,
|
||||
headers=response.headers, content=TimedContent())
|
||||
else:
|
||||
response_for_relay = response
|
||||
return await relay.relay_api(request, response_for_relay, requested_model='test-model')
|
||||
|
||||
proxy_app = web.Application()
|
||||
proxy_app.router.add_post(path, proxy)
|
||||
client = TestClient(TestServer(proxy_app))
|
||||
await client.start_server()
|
||||
try:
|
||||
async with client.post(path, data=b'{"stream":true}') as response:
|
||||
body = await asyncio.wait_for(response.read(), 3)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(len(calls), 1, 'partial or ambiguous generations must never replay')
|
||||
return body, response.headers['X-Request-ID']
|
||||
finally:
|
||||
release.set()
|
||||
await client.close()
|
||||
await session.close()
|
||||
await server.close()
|
||||
|
||||
def assert_interrupted(self, body, prefix, request_id):
|
||||
self.assertTrue(body.startswith(prefix), 'preserve all already received complete frames byte-exact')
|
||||
suffix = body[len(prefix):]
|
||||
self.assertTrue(suffix.startswith(b'event: error\ndata: '))
|
||||
payload = json.loads(suffix.split(b'data: ', 1)[1])
|
||||
self.assertEqual(payload['error']['code'], 'upstream_stream_incomplete')
|
||||
self.assertIs(payload['error']['retryable'], False)
|
||||
self.assertEqual(payload['error']['gateway_request_id'], request_id)
|
||||
self.assertNotIn(b'[DONE]', suffix)
|
||||
self.assertNotIn(b'finish_reason', suffix)
|
||||
|
||||
async def test_clean_eof_after_partial_content_is_explicit_nonretryable_error(self):
|
||||
partial = b'data: {"model":"test-model","choices":[{"delta":{"content":"def resolve"}}]}\n\n'
|
||||
body, rid = await self.exercise([partial])
|
||||
self.assert_interrupted(body, partial, rid)
|
||||
|
||||
async def test_upstream_disconnect_preserves_partial_and_reports_error(self):
|
||||
partial = b'data: {"model":"test-model","choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
body, rid = await self.exercise([partial], abort=True)
|
||||
self.assert_interrupted(body, partial, rid)
|
||||
|
||||
async def test_upstream_idle_timeout_is_not_clean_success_or_replayed(self):
|
||||
partial = b'data: {"model":"test-model","choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
body, rid = await self.exercise([partial], timeout=True)
|
||||
self.assert_interrupted(body, partial, rid)
|
||||
|
||||
async def test_done_is_byte_exact_and_never_gets_synthetic_finish(self):
|
||||
complete = b'data: {"model":"test-model","choices":[{"delta":{"content":"OK"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n'
|
||||
body, _ = await self.exercise([complete])
|
||||
self.assertEqual(body, complete)
|
||||
|
||||
async def test_done_without_final_separator_at_eof_is_preserved(self):
|
||||
complete = b'data: {"model":"test-model","choices":[{"delta":{},"finish_reason":"length"}]}\n\ndata: [DONE]'
|
||||
body, _ = await self.exercise([complete])
|
||||
self.assertEqual(body, complete)
|
||||
|
||||
async def test_finish_reason_without_done_is_still_incomplete_transport(self):
|
||||
# A finished choice does not prove usage/tail delivery. Fail closed on
|
||||
# missing protocol terminal; preserve the real finish frame verbatim.
|
||||
complete_choice = b'data: {"model":"test-model","choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'
|
||||
body, rid = await self.exercise([complete_choice])
|
||||
self.assert_interrupted(body, complete_choice, rid)
|
||||
|
||||
async def test_native_responses_protocol_does_not_require_chat_done(self):
|
||||
complete = b'event: response.completed\ndata: {"type":"response.completed","model":"test-model"}\n\n'
|
||||
body, _ = await self.exercise([complete], path='/v1/responses')
|
||||
self.assertEqual(body, complete)
|
||||
|
||||
async def test_provider_error_does_not_get_second_error(self):
|
||||
provider = b'data: {"error":{"message":"private provider failure","status":503}}\n\n'
|
||||
mapped, terminal = relay.safe_sse_frame(provider[:-2], '/v1/chat/completions', 'test-model')
|
||||
self.assertTrue(terminal)
|
||||
body, _ = await self.exercise([provider])
|
||||
self.assertEqual(body, mapped + b'\n\n')
|
||||
|
||||
async def test_partial_json_eof_never_encourages_paid_replay(self):
|
||||
complete_frame = b'data: {"model":"test-model","choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
body, _ = await self.exercise([complete_frame + b'data: {"model":"test-model"'])
|
||||
self.assertTrue(body.startswith(complete_frame))
|
||||
suffix = body[len(complete_frame):]
|
||||
payload = json.loads(suffix.split(b'data: ', 1)[1])
|
||||
self.assertEqual(payload['error']['code'], 'upstream_unparseable_response')
|
||||
self.assertIs(payload['error']['retryable'], False)
|
||||
self.assertNotIn(b'[DONE]', suffix)
|
||||
|
||||
async def test_legacy_completions_eof_uses_the_same_nonretryable_error(self):
|
||||
partial = b'data: {"model":"test-model","choices":[{"text":"partial","index":0}]}\n\n'
|
||||
body, rid = await self.exercise([partial], path='/v1/completions')
|
||||
self.assert_interrupted(body, partial, rid)
|
||||
|
||||
async def test_valid_eof_frame_is_separated_from_error(self):
|
||||
partial = b'data: {"model":"test-model","choices":[{"delta":{"content":"partial"}}]}'
|
||||
body, rid = await self.exercise([partial])
|
||||
self.assert_interrupted(body, partial + b'\n\n', rid)
|
||||
|
||||
|
||||
class ErrorLogPrivacyTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_raw_provider_error_never_logged(self):
|
||||
class Content:
|
||||
async def iter_chunked(self, size):
|
||||
yield canary
|
||||
class Upstream:
|
||||
status = 503
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
content = Content()
|
||||
request = type('Request', (), {'path': '/v1/chat/completions', 'headers': {}})()
|
||||
canary = b'{"error":{"message":"private-canary-user-prompt-and-key","code":"upstream_error"}}'
|
||||
with self.assertLogs('gateway_proxy', level='WARNING') as captured:
|
||||
response = await relay.relay_api(request, Upstream(), requested_model='test-model')
|
||||
self.assertGreaterEqual(response.status, 400)
|
||||
logs = '\n'.join(captured.output)
|
||||
self.assertNotIn('private-canary-user-prompt-and-key', logs)
|
||||
self.assertIn('api_error', logs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,105 @@
|
||||
"""Runtime contracts: finish at the SSE terminal marker, never at finish_reason alone."""
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
ROOT = Path(os.environ.get('IISHKO_SNAPSHOT_ROOT', Path(__file__).resolve().parents[1] / 'gateway'))
|
||||
sys.path.insert(0, str(ROOT))
|
||||
spec = importlib.util.spec_from_file_location('terminal_relay_under_test', ROOT / 'transparent_api.py')
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError('Cannot load relay module from snapshot')
|
||||
relay_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(relay_module)
|
||||
|
||||
|
||||
class TerminalStreamTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def exercise(self, parts, expected, *, hold_after=True):
|
||||
release = asyncio.Event()
|
||||
upstream_sent = asyncio.Event()
|
||||
calls = []
|
||||
|
||||
async def upstream(request):
|
||||
calls.append(await request.read())
|
||||
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
for part in parts:
|
||||
await response.write(part)
|
||||
await asyncio.sleep(0)
|
||||
upstream_sent.set()
|
||||
if hold_after:
|
||||
await release.wait()
|
||||
try:
|
||||
await response.write_eof()
|
||||
except (ConnectionResetError, aiohttp.ClientError):
|
||||
pass
|
||||
return response
|
||||
|
||||
upstream_app = web.Application()
|
||||
upstream_app.router.add_post('/v1/chat/completions', upstream)
|
||||
upstream_server = TestServer(upstream_app)
|
||||
await upstream_server.start_server()
|
||||
session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10))
|
||||
|
||||
async def proxy(request):
|
||||
async with session.post(upstream_server.make_url(request.path),
|
||||
data=await request.read()) as response:
|
||||
return await relay_module.relay_api(request, response, requested_model='test-model')
|
||||
|
||||
proxy_app = web.Application()
|
||||
proxy_app.router.add_post('/v1/chat/completions', proxy)
|
||||
client = TestClient(TestServer(proxy_app))
|
||||
await client.start_server()
|
||||
try:
|
||||
async with client.post('/v1/chat/completions', data=b'{"stream":true}') as response:
|
||||
await asyncio.wait_for(upstream_sent.wait(), 3)
|
||||
body = await asyncio.wait_for(response.read(), 1)
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(body, expected)
|
||||
self.assertEqual(len(calls), 1, 'terminal handling must never replay generation')
|
||||
self.assertEqual(response.headers.get('Content-Type'), 'text/event-stream')
|
||||
finally:
|
||||
release.set()
|
||||
await client.close()
|
||||
await session.close()
|
||||
await upstream_server.close()
|
||||
|
||||
async def test_done_closes_without_upstream_eof(self):
|
||||
raw = b'data: {"model":"test-model","choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n'
|
||||
await self.exercise([raw], raw)
|
||||
|
||||
async def test_fragmented_crlf_done_is_byte_exact(self):
|
||||
parts = [b': keepalive\r\n\r\ndata: {"model":"test-model","choices":[]}\r\n\r\ndata: [DO', b'NE]\r', b'\n\r\n']
|
||||
await self.exercise(parts, b''.join(parts))
|
||||
|
||||
async def test_usage_after_finish_reason_is_preserved(self):
|
||||
parts = [b'data: {"model":"test-model","choices":[{"delta":{},"finish_reason":"stop"}]}\n\n',
|
||||
b'data: {"model":"test-model","choices":[],"usage":{"total_tokens":9}}\n\n',
|
||||
b'data: [DONE]\n\n']
|
||||
await self.exercise(parts, b''.join(parts))
|
||||
|
||||
async def test_done_suffix_bytes_are_not_forwarded(self):
|
||||
terminal = b'data: [DONE]\n\n'
|
||||
await self.exercise([terminal + b'data: {"error":{"message":"late"}}\n\n'], terminal)
|
||||
|
||||
async def test_text_containing_done_is_not_terminal(self):
|
||||
raw = b'data: {"model":"test-model","choices":[{"delta":{"content":"[DONE]"}}]}\n\n'
|
||||
# A literal in content must not close the stream before its real marker.
|
||||
terminal = b'data: [DONE]\n\n'
|
||||
await self.exercise([raw, terminal], raw + terminal)
|
||||
|
||||
async def test_provider_error_still_terminates(self):
|
||||
raw = b'data: {"error":{"message":"upstream failure","status":503}}\n\n'
|
||||
mapped, terminal = relay_module.safe_sse_frame(raw[:-2], '/v1/chat/completions', 'test-model')
|
||||
self.assertTrue(terminal)
|
||||
await self.exercise([raw], mapped + b'\n\n')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Regression tests for gateway `_tg_store_conn` ALTER seized migration.
|
||||
|
||||
`gateway/grok-web-skin.py` is an executable aiohttp script with module-level
|
||||
side effects, so the migration function is AST-extracted and executed in an
|
||||
isolated namespace against temp SQLite databases and small fakes.
|
||||
|
||||
Contract under test: only a real duplicate-column OperationalError is benign;
|
||||
any other OperationalError must be re-raised after the connection is closed,
|
||||
and `_TG_SCHEMA_READY` must stay False.
|
||||
|
||||
The base schema is pre-seeded in the failure tests so that every statement
|
||||
before the ALTER is a guaranteed no-op and the ALTER is the first write
|
||||
attempt; otherwise the error would surface on `CREATE TABLE IF NOT EXISTS`
|
||||
outside the guarded block and the close-on-failure assertion would be moot.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GATEWAY = ROOT / "gateway" / "grok-web-skin.py"
|
||||
|
||||
_BASE_DDL = (
|
||||
"CREATE TABLE IF NOT EXISTS tg_users("
|
||||
"tg_id INTEGER PRIMARY KEY, username TEXT, password TEXT, created INTEGER)",
|
||||
"CREATE TABLE IF NOT EXISTS tg_share_events("
|
||||
"user_id INTEGER, key TEXT, day TEXT, ts INTEGER, "
|
||||
"PRIMARY KEY(user_id, key, day))",
|
||||
"CREATE TABLE IF NOT EXISTS ip_claims("
|
||||
"ip TEXT NOT NULL, token_name TEXT NOT NULL, "
|
||||
"first_seen INTEGER NOT NULL, last_seen INTEGER NOT NULL, "
|
||||
"PRIMARY KEY(ip, token_name))",
|
||||
"CREATE INDEX IF NOT EXISTS ip_claims_by_ip ON ip_claims(ip)",
|
||||
"CREATE TABLE IF NOT EXISTS ip_lock_events("
|
||||
"ip TEXT, token_name TEXT, action TEXT, detail TEXT, ts INTEGER)",
|
||||
)
|
||||
|
||||
|
||||
def _extract_source() -> str:
|
||||
text = GATEWAY.read_text(encoding="utf-8")
|
||||
tree = ast.parse(text, filename=str(GATEWAY))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_tg_store_conn":
|
||||
return ast.get_source_segment(text, node)
|
||||
pytest.fail("_tg_store_conn not found in gateway/grok-web-skin.py")
|
||||
|
||||
|
||||
class _Cursor:
|
||||
def fetchone(self):
|
||||
return None
|
||||
|
||||
def fetchall(self):
|
||||
return []
|
||||
|
||||
|
||||
class _TrackedConnection:
|
||||
"""Delegates to a real sqlite3 connection and records close()."""
|
||||
|
||||
def __init__(self, con):
|
||||
self._con = con
|
||||
self.closed = False
|
||||
|
||||
def execute(self, *args, **kwargs):
|
||||
if self.closed:
|
||||
raise sqlite3.ProgrammingError("Cannot operate on a closed database.")
|
||||
return self._con.execute(*args, **kwargs)
|
||||
|
||||
def commit(self):
|
||||
return self._con.commit()
|
||||
|
||||
def close(self):
|
||||
if not self.closed:
|
||||
self.closed = True
|
||||
self._con.close()
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._con, name)
|
||||
|
||||
|
||||
class _ScriptedConnection(_TrackedConnection):
|
||||
"""Raises a chosen OperationalError on the ALTER statement."""
|
||||
|
||||
def __init__(self, error, trigger="ALTER TABLE"):
|
||||
self.error = error
|
||||
self.trigger = trigger
|
||||
self._con = None
|
||||
self.closed = False
|
||||
|
||||
def execute(self, sql, *args, **kwargs):
|
||||
if self.trigger in sql:
|
||||
raise self.error
|
||||
return _Cursor()
|
||||
|
||||
def commit(self):
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _SqliteModule:
|
||||
OperationalError = sqlite3.OperationalError
|
||||
ProgrammingError = sqlite3.ProgrammingError
|
||||
|
||||
def __init__(self, connect):
|
||||
self.connect = connect
|
||||
|
||||
|
||||
def _load(connect, db_path, created):
|
||||
def tracking_connect(path, *args, **kwargs):
|
||||
con = connect(path, *args, **kwargs)
|
||||
created.append(con)
|
||||
return con
|
||||
|
||||
ns = {
|
||||
"__name__": "gateway_tg_store_probe",
|
||||
"sqlite3": _SqliteModule(tracking_connect),
|
||||
"os": os,
|
||||
"TG_PROVISION_DB": str(db_path),
|
||||
"_TG_SCHEMA_READY": False,
|
||||
}
|
||||
exec(compile(_extract_source(), "<gateway _tg_store_conn>", "exec"), ns, ns)
|
||||
return ns, ns["_tg_store_conn"]
|
||||
|
||||
|
||||
def _seed_base(db: Path) -> None:
|
||||
con = sqlite3.connect(db)
|
||||
for statement in _BASE_DDL:
|
||||
con.execute(statement)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def test_duplicate_column_is_ignored(tmp_path):
|
||||
db = tmp_path / "provision.db"
|
||||
_seed_base(db)
|
||||
seed = sqlite3.connect(db)
|
||||
seed.execute("ALTER TABLE tg_share_events ADD COLUMN seized INTEGER DEFAULT 0")
|
||||
seed.commit()
|
||||
seed.close()
|
||||
|
||||
created = []
|
||||
|
||||
def connect_tracked(path, *args, **kwargs):
|
||||
return _TrackedConnection(sqlite3.connect(path, *args, **kwargs))
|
||||
|
||||
ns, fn = _load(connect_tracked, db, created)
|
||||
con = fn()
|
||||
try:
|
||||
assert ns["_TG_SCHEMA_READY"] is True
|
||||
assert created[0].closed is False
|
||||
columns = {
|
||||
row[1] for row in con.execute("PRAGMA table_info(tg_share_events)")
|
||||
}
|
||||
assert "seized" in columns
|
||||
assert con.execute("SELECT 1 FROM ip_claims LIMIT 1").fetchone() is None
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def test_locked_database_reraises_and_closes(tmp_path):
|
||||
db = tmp_path / "provision.db"
|
||||
_seed_base(db)
|
||||
|
||||
holder = sqlite3.connect(db, isolation_level=None)
|
||||
holder.execute("BEGIN IMMEDIATE")
|
||||
created = []
|
||||
|
||||
def connect_no_wait(path, *args, **kwargs):
|
||||
kwargs.pop("timeout", None)
|
||||
return _TrackedConnection(sqlite3.connect(path, timeout=0, **kwargs))
|
||||
|
||||
ns, fn = _load(connect_no_wait, db, created)
|
||||
try:
|
||||
with pytest.raises(sqlite3.OperationalError, match="locked"):
|
||||
fn()
|
||||
finally:
|
||||
holder.execute("ROLLBACK")
|
||||
holder.close()
|
||||
|
||||
assert ns["_TG_SCHEMA_READY"] is False
|
||||
assert created and created[0].closed is True
|
||||
|
||||
|
||||
def test_readonly_database_reraises_and_closes(tmp_path):
|
||||
db = tmp_path / "provision.db"
|
||||
_seed_base(db)
|
||||
created = []
|
||||
|
||||
def connect_ro(path, *args, **kwargs):
|
||||
uri = Path(path).resolve().as_uri() + "?mode=ro"
|
||||
return _TrackedConnection(sqlite3.connect(uri, uri=True))
|
||||
|
||||
ns, fn = _load(connect_ro, db, created)
|
||||
with pytest.raises(sqlite3.OperationalError):
|
||||
fn()
|
||||
|
||||
assert ns["_TG_SCHEMA_READY"] is False
|
||||
assert created and created[0].closed is True
|
||||
|
||||
|
||||
def test_unrelated_operational_error_is_not_swallowed(tmp_path):
|
||||
db = tmp_path / "provision.db"
|
||||
created = []
|
||||
|
||||
def connect_scripted(path, *args, **kwargs):
|
||||
return _ScriptedConnection(
|
||||
sqlite3.OperationalError("database disk image is malformed")
|
||||
)
|
||||
|
||||
ns, fn = _load(connect_scripted, db, created)
|
||||
with pytest.raises(sqlite3.OperationalError, match="malformed"):
|
||||
fn()
|
||||
|
||||
assert ns["_TG_SCHEMA_READY"] is False
|
||||
assert created and created[0].closed is True
|
||||
@@ -0,0 +1,281 @@
|
||||
"""Contracts for the minimal public-API hotfix; no production access."""
|
||||
import ast
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import sys
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
from multidict import CIMultiDict
|
||||
from yarl import URL
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway'))
|
||||
from gateway_errors import HOP_HEADERS, key_from_headers, normalize_auth_headers, public_error, public_json_dumps
|
||||
from transparent_api import relay_api
|
||||
# [EFFORT-SCHEMA 2026-10-28] skin's guarded import resolves to the real parser; the
|
||||
# extracted proxy must see the same symbols, not a stub.
|
||||
from request_effort import InvalidEffort, read_effort
|
||||
|
||||
SKIN = ROOT / 'gateway/grok-web-skin.py'
|
||||
|
||||
|
||||
def extract(path, names, namespace):
|
||||
tree = ast.parse(path.read_text(encoding='utf-8'))
|
||||
nodes = [node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.name in names]
|
||||
if {node.name for node in nodes} != set(names):
|
||||
raise AssertionError('Requested live entrypoints missing')
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), 'exec'), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
class PublicTransparentTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
self.seen = []
|
||||
self.status, self.answer, self.mode = 200, b'{ "model":"gpt-6.1-sol", "answer":"CodAI original" }', 'json'
|
||||
self.up_headers = {'Content-Type': 'application/json'}
|
||||
|
||||
async def target(request):
|
||||
self.seen.append((request.method, request.raw_path, await request.read(), dict(request.headers)))
|
||||
if self.mode == 'disconnect':
|
||||
request.transport.close()
|
||||
return web.Response()
|
||||
if self.mode == 'sse':
|
||||
response = web.StreamResponse(status=self.status, headers={'Content-Type': 'text/event-stream'})
|
||||
await response.prepare(request)
|
||||
midpoint = len(self.answer) // 2
|
||||
await response.write(self.answer[:midpoint])
|
||||
await asyncio.sleep(0)
|
||||
await response.write(self.answer[midpoint:])
|
||||
await response.write_eof()
|
||||
return response
|
||||
return web.Response(status=self.status, body=self.answer, headers=self.up_headers)
|
||||
|
||||
upstream = web.Application()
|
||||
upstream.router.add_route('*', '/{path:.*}', target)
|
||||
self.target = TestServer(upstream)
|
||||
await self.target.start_server()
|
||||
self.session = aiohttp.ClientSession()
|
||||
key = web.AppKey('urgent_test_session', aiohttp.ClientSession)
|
||||
self.app = web.Application(client_max_size=1024)
|
||||
self.app[key] = self.session
|
||||
self.ns = {
|
||||
'aiohttp': aiohttp, 'asyncio': asyncio, 'web': web, 'ClientSession': aiohttp.ClientSession,
|
||||
'URL': URL, 'json': json, 'CIMultiDict': CIMultiDict, 'HOP_HEADERS': HOP_HEADERS,
|
||||
'normalize_auth_headers': normalize_auth_headers, 'relay_api': relay_api,
|
||||
'key_from_headers': key_from_headers,
|
||||
'read_effort': read_effort, 'InvalidEffort': InvalidEffort,
|
||||
'PROVIDER_KEY': web.AppKey('test_providers', object),
|
||||
'UPSTREAM': str(self.target.make_url('')).rstrip('/'), 'SESSION_KEY': key,
|
||||
'TIMEOUT': aiohttp.ClientTimeout(total=5), 'SKIP': ('/v1/',),
|
||||
'_GEN_PATHS': {'/v1/chat/completions', '/v1/messages', '/v1/responses'},
|
||||
'LOG': logging.getLogger('transparent_test'),
|
||||
'gate_check': AsyncMock(return_value=(False, '')), '_rl_check_sync': Mock(return_value=None),
|
||||
'_DEV_ROLE_INCOMPAT_PREFIXES': ("qwen", "glm", "deepseek", "kimi"),
|
||||
'_key_balance_usd': Mock(return_value=None),
|
||||
'_tg_resolve_site_user': Mock(return_value=None), '_tg_key_owner': Mock(return_value=None),
|
||||
'_key_share_seize': Mock(side_effect=AssertionError('Must not touch wallet')),
|
||||
'_ip_lock_check': AsyncMock(side_effect=AssertionError('No sticky IP binding')),
|
||||
'_fix_reasoning_effort': Mock(side_effect=AssertionError('Body must remain byte-exact')),
|
||||
'relay': AsyncMock(side_effect=AssertionError('Legacy rewriting relay reached')),
|
||||
'error_response': lambda status, raw, path, api_key=None: web.json_response({'error': {'origin': 'local'}}, status=status),
|
||||
}
|
||||
self.ns['__name__'] = 'offline_skin_api_regression'
|
||||
tree = ast.parse(SKIN.read_text(encoding='utf-8'))
|
||||
names = {'CONTROL_SESSION_KEY', 'GENERATION_CONNECTIONS', 'CONTROL_CONNECTIONS'}
|
||||
constants = [node for node in tree.body if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id in names for target in node.targets)]
|
||||
exec(compile(ast.Module(body=constants, type_ignores=[]), str(SKIN), 'exec'), self.ns)
|
||||
extract(SKIN, {'proxy', 'response_headers', '_dev_role_incompat_model',
|
||||
'_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions'}, self.ns)
|
||||
self.app.router.add_route('*', '/{path:.*}', self.ns['proxy'])
|
||||
self.client = TestClient(TestServer(self.app))
|
||||
await self.client.start_server()
|
||||
|
||||
async def asyncTearDown(self):
|
||||
await self.client.close()
|
||||
await self.ns['_close_upstream_sessions'](self.app)
|
||||
await self.target.close()
|
||||
|
||||
def headers(self):
|
||||
return {'Authorization': 'Bearer offline-key', 'Content-Type': 'application/json'}
|
||||
|
||||
async def test_system_developer_tools_reasoning_and_raw_path_are_exact(self):
|
||||
body = b'{ "model":"gpt-6.1-sol", "messages":[{"role":"system","content":"KEEP system"},{"role":"developer","content":"KEEP developer"}], "tools":[{"type":"function","function":{"name":"native_tool"}}], "reasoning_effort":"minimal" }'
|
||||
url = URL(str(self.client.make_url('/')).rstrip('/') + '/v1/chat%2Fcompletions?x=%2F&k=1&k=2&s=a%20b', encoded=True)
|
||||
response = await self.client.session.post(url, data=body, headers=self.headers())
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(await response.read(), self.answer)
|
||||
self.assertEqual(self.seen[0][1], '/v1/chat%2Fcompletions?x=%2F&k=1&k=2&s=a%20b')
|
||||
self.assertEqual(self.seen[0][2], body)
|
||||
self.ns['_fix_reasoning_effort'].assert_not_called()
|
||||
self.ns['_ip_lock_check'].assert_not_called()
|
||||
self.ns['_key_share_seize'].assert_not_called()
|
||||
|
||||
async def test_http_errors_are_normalized_without_replaying_requests(self):
|
||||
cases = ((200, 503, 'upstream_unavailable', True),
|
||||
(400, 400, 'invalid_request', False),
|
||||
(401, 401, 'invalid_api_key', False),
|
||||
(403, 403, 'request_forbidden', False),
|
||||
(413, 413, 'upstream_request_too_large', False),
|
||||
(429, 429, 'upstream_busy', True),
|
||||
(503, 503, 'upstream_unavailable', True))
|
||||
for status, expected_status, code, retryable in cases:
|
||||
with self.subTest(status=status):
|
||||
self.status = status
|
||||
self.answer = b'{ "error": {"message":"CodAI refuses original request", "code":"provider_original"} }'
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{"model":"gpt-6.1-sol"}', headers=self.headers())
|
||||
self.assertEqual(response.status, expected_status)
|
||||
raw = await response.read()
|
||||
body = json.loads(raw)
|
||||
self.assertEqual(body['error']['code'], code)
|
||||
self.assertIs(body['error']['retryable'], retryable)
|
||||
self.assertNotIn(b'CodAI', raw)
|
||||
self.assertNotIn(b'\\u04', raw)
|
||||
self.assertNotIn('choices', body)
|
||||
self.assertTrue(response.headers.get('X-Request-ID'))
|
||||
self.assertEqual(len(self.seen), len(cases))
|
||||
|
||||
async def test_successful_sse_tool_calls_and_done_are_byte_exact(self):
|
||||
self.mode = 'sse'
|
||||
self.answer = b'data: {"model":"codai-fast","choices":[{"delta":{"tool_calls":[{"function":{"name":"native_tool","arguments":"{}"}}]}}]}\n\ndata: [DONE]\n\n'
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{}', headers=self.headers())
|
||||
self.assertEqual(await response.read(), self.answer)
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
async def test_sse_rechecks_model_after_valid_frames_without_replay(self):
|
||||
self.mode = 'sse'
|
||||
valid = b'data: { "model":"anthropic/claude-opus-5.5", "choices":[{"delta":{"content":"kept"}}]}\r\n\r\n'
|
||||
replaced = b'data: {"model":"claude-sonnet-5.5","choices":[{"delta":{"content":"replaced"}}]}\n\n'
|
||||
self.answer = valid * 8 + replaced + b'data: [DONE]\n\n'
|
||||
response = await self.client.post(
|
||||
'/v1/chat/completions', data=b'{"model":"claude-5-5-opus"}',
|
||||
headers=self.headers())
|
||||
raw = await response.read()
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertTrue(raw.startswith(valid * 8))
|
||||
self.assertIn(b'model_identity_mismatch', raw)
|
||||
self.assertNotIn(b'replaced', raw)
|
||||
self.assertNotIn(b'[DONE]', raw)
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
async def test_sse_error_is_safe_and_does_not_fabricate_completion(self):
|
||||
self.mode = 'sse'
|
||||
self.answer = b'data: {"error":{"message":"CodAI private error"}}\n\ndata: [DONE]\n\n'
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{}', headers=self.headers())
|
||||
raw = await response.read()
|
||||
self.assertIn(b'event: error', raw)
|
||||
self.assertIn(b'upstream_unavailable', raw)
|
||||
self.assertNotIn(b'CodAI', raw)
|
||||
self.assertNotIn(b'[DONE]', raw)
|
||||
self.assertNotIn(b'\\u04', raw)
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
async def test_compressed_and_binary_responses_are_not_decoded_or_truncated(self):
|
||||
self.answer = gzip.compress(bytes(range(256)) * 30, mtime=0)
|
||||
self.up_headers = {'Content-Type': 'application/octet-stream', 'Content-Encoding': 'gzip'}
|
||||
response = await self.client.post('/v1/responses', data=b'{}', headers=self.headers(), auto_decompress=False)
|
||||
self.assertEqual(await response.read(), self.answer)
|
||||
self.assertEqual(response.headers['Content-Encoding'], 'gzip')
|
||||
|
||||
async def test_authentication_alias_is_normalized_once_without_forwarding_conflicts(self):
|
||||
response = await self.client.post('/v1/messages', data=b'{}', headers={'X-Api-Key': 'offline-key'})
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(self.seen[0][3]['Authorization'], 'Bearer offline-key')
|
||||
self.assertNotIn('X-Api-Key', self.seen[0][3])
|
||||
response = await self.client.post('/v1/messages', data=b'{}', headers={'Authorization': 'Bearer offline-key', 'X-Api-Key': 'different-key'})
|
||||
self.assertEqual(response.status, 400)
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
async def test_daily_limit_and_access_controls_remain_enforced(self):
|
||||
self.ns['_rl_check_sync'].return_value = (429, 'Daily budget exceeded; balance saved')
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{"model":"glm-5.3"}', headers=self.headers())
|
||||
self.assertEqual(response.status, 429)
|
||||
self.assertEqual((await response.json())['error']['code'], 'daily_limit')
|
||||
self.assertFalse(self.seen)
|
||||
self.ns['_rl_check_sync'].return_value = None
|
||||
self.ns['gate_check'].return_value = (True, 'Account blocked')
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{}', headers=self.headers())
|
||||
self.assertEqual(response.status, 403)
|
||||
self.assertFalse(self.seen)
|
||||
|
||||
async def test_site_account_mismatch_does_not_seize_funds(self):
|
||||
self.ns['_tg_resolve_site_user'].return_value = (42, 'tg42')
|
||||
self.ns['_tg_key_owner'].return_value = (43, 'tg43')
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{}', headers={**self.headers(), 'Cookie': 'tg_sid=signed-test-cookie'})
|
||||
self.assertEqual(response.status, 403)
|
||||
self.assertFalse(self.seen)
|
||||
self.ns['_key_share_seize'].assert_not_called()
|
||||
self.assertNotIn('изъят', (await response.json())['error']['message'])
|
||||
|
||||
async def test_disconnected_upstream_post_is_not_replayed(self):
|
||||
self.mode = 'disconnect'
|
||||
response = await self.client.post('/v1/chat/completions', data=b'{}', headers=self.headers())
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
async def test_oversized_local_body_is_413_without_upstream_request(self):
|
||||
response = await self.client.post('/v1/chat/completions', data=b'x' * 2048, headers=self.headers())
|
||||
self.assertEqual(response.status, 413)
|
||||
self.assertFalse(self.seen)
|
||||
|
||||
async def test_managed_model_without_explicit_pin_uses_ordinary_billed_route(self):
|
||||
self.app[self.ns['PROVIDER_KEY']] = SimpleNamespace(
|
||||
providers=[{'models': {'gpt-6.1-sol': {}}}], pinning_enabled=True)
|
||||
selected = self.ns['relay_selected'] = AsyncMock(
|
||||
side_effect=AssertionError('Ordinary users must not enter admin-only pinning'))
|
||||
response = await self.client.post('/v1/chat/completions',
|
||||
data=b'{"model":"gpt-6.1-sol"}', headers=self.headers())
|
||||
self.assertEqual(response.status, 200)
|
||||
self.assertEqual(await response.read(), self.answer)
|
||||
selected.assert_not_awaited()
|
||||
self.assertEqual(len(self.seen), 1)
|
||||
|
||||
|
||||
class PublicErrorWireTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_rewritten_error_drops_upstream_framing_encoding_and_cookies(self):
|
||||
namespace = {
|
||||
'web': web, 'secrets': secrets, 'CIMultiDict': CIMultiDict,
|
||||
'public_error': public_error, 'public_json_dumps': public_json_dumps,
|
||||
'LOG': logging.getLogger('error_wire_test'),
|
||||
}
|
||||
extract(SKIN, {'error_response'}, namespace)
|
||||
|
||||
async def handler(request):
|
||||
return namespace['error_response'](
|
||||
503, b'provider unavailable', request.path, from_upstream=True,
|
||||
headers={'Content-Length': '7', 'Transfer-Encoding': 'chunked',
|
||||
'Content-Encoding': 'gzip', 'Content-Type': 'text/private',
|
||||
'Connection': 'close', 'Set-Cookie': 'fixture=do-not-forward',
|
||||
'Retry-After': '17', 'X-Request-ID': 'upstream-fixture'})
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_post('/v1/messages', handler)
|
||||
client = TestClient(TestServer(app))
|
||||
await client.start_server()
|
||||
try:
|
||||
for _ in range(2):
|
||||
response = await client.post('/v1/messages', data=b'{}')
|
||||
raw = await response.read()
|
||||
payload = json.loads(raw)
|
||||
self.assertEqual(response.status, 503)
|
||||
self.assertEqual(int(response.headers['Content-Length']), len(raw))
|
||||
self.assertEqual(response.headers['X-Request-ID'], payload['error']['request_id'])
|
||||
self.assertEqual(response.headers['Retry-After'], '17')
|
||||
self.assertEqual(response.headers['Cache-Control'], 'no-store')
|
||||
for name in ('Content-Encoding', 'Transfer-Encoding', 'Set-Cookie', 'Connection'):
|
||||
self.assertNotIn(name, response.headers)
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user