Files
iishko-public/tests/test_gateway_commerce.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

327 lines
20 KiB
Python

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