Files
iishko-public/tests/test_key_quota_recovery.py
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

266 lines
13 KiB
Python

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)