Files
iishko-public/tests/test_commerce_access.py
T
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

112 lines
6.3 KiB
Python

"""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()