Files
iishko-public/tests/test_account_balances.py
Vlad Gothbreach af292ff15d
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
Harden entry safety, unify runtime config, bound document unpacking
Shared-IP safety: entry autoban and entry notifications default off, and a
shared IP is treated as review evidence only. ban_user/ban_cluster refuse
reason=entry_ip_collision (also with the legacy flag set to 1), so token status
and quota are never touched; explicit admin moderation still works.

Reproducible startup: new bot/runtime_config.py and scripts/run.py load the
repository .env (or --env-file) without shell interpolation, normalize
config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap,
account admin, mk_daemon, entry admin and key notifications resolve the same
paths. "run.py <target> --check" is an offline preflight that starts nothing
and reports placeholders, missing upstream DB and invalid data directories.

Resource limits: aggregate Office decompression, a 400 read-entry cap and a
per-row XLSX cell budget stop early; truncated or corrupt archives are
reported instead of raising.

Deploy and docs: only source-backed systemd units remain, and
deploy/runtime.env.example documents the environment contract including the
0600 session-secret file rules. Removed the destructive
"cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/
snapshot and the unsupported iishko-ts staging unit; corrected .env.example,
README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md.

Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy
contract, abilities_guard CLI, and a startup smoke that launches all three
components through scripts/run.py with non-loopback network blocked. Every
config reader, selfcheck included, accepts a UTF-8 BOM.

Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73,
go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and
history 0 findings. No production or live-split changes are included.
2026-10-31 00:39:35 +03:00

145 lines
8.3 KiB
Python

"""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,
econ_state_path=lambda: str(Path(temp.name) / 'econ_state.json'),
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()