Make legacy payment delivery retryable and keep gateway paths responsive
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

This commit is contained in:
Vlad Gothbreach
2026-10-31 11:23:33 +03:00
parent 97d125122c
commit 3765b00b52
13 changed files with 2854 additions and 303 deletions
+18 -3
View File
@@ -179,6 +179,7 @@ unit-файлов, но сам `.env` не загружает; окружени
| Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) | | Персистентный контекст чата | `IISHKO_MEMORY_OFF` | `1` (без памяти) |
| Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена | | Геолокация по IP (DB-IP) | файл `bot/geo/*.mmdb` | нет файла → функция выключена |
| Платежи и покупки (CryptoPay / xRocket) | `commerce_offers` + `cryptopay_token` в `bot/config.json`, env `CRYPTOPAY_TOKEN` (имеет приоритет) | `commerce_offers: []` и пустой токен → покупки и создание платежей недоступны; дефолтных цен нет | | Платежи и покупки (CryptoPay / xRocket) | `commerce_offers` + `cryptopay_token` в `bot/config.json`, env `CRYPTOPAY_TOKEN` (имеет приоритет) | `commerce_offers: []` и пустой токен → покупки и создание платежей недоступны; дефолтных цен нет |
| Legacy-товары (покупка ранга, донат-безлимит) | `legacy_products` в `bot/config.json` | `false` → новые счета не создаются; `commerce_offers: []` выключает их даже при `true`. Доставка оплаченного работает всегда |
| Community board (`/api/activities`) | — (переключателя нет) | маршруты включены; доступ ограничен auth/ban/admin-гейтами | | Community board (`/api/activities`) | — (переключателя нет) | маршруты включены; доступ ограничен auth/ban/admin-гейтами |
| Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах | | Чтение кошелька и grants | — (переключателя нет) | работает и при пустых офферах |
| Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) | | Премиум-эмодзи в рассылках | `IISHKO_BC_PREMIUM_AUTOFILL` | `0` (выкл.) |
@@ -249,10 +250,24 @@ node --test tests/*.mjs # Node-тесты (Node 22), есл
* **Docker-смоуков.** Никаких контейнерных прогонов здесь не выполнялось и не заявляется. * **Docker-смоуков.** Никаких контейнерных прогонов здесь не выполнялось и не заявляется.
* **Платежей из коробки.** Покупки и создание платежей недоступны, пока в * **Платежей из коробки.** Покупки и создание платежей недоступны, пока в
`bot/config.json` не заданы `commerce_offers` и платёжный токен (`cryptopay_token`, `bot/config.json` не заданы `commerce_offers` и платёжный токен (`cryptopay_token`,
env `CRYPTOPAY_TOKEN` имеет приоритет). Дефолтных цен в коде нет. env `CRYPTOPAY_TOKEN` имеет приоритет). У commerce-офферов нет дефолтных цен в коде.
**Enable-флагов у commerce нет**: `community_board` и `account_balances` не **Legacy-товары** (покупка ранга `/buyrank`, донат-безлимит `/donate`) несут собственные
цены в коде, поэтому закрыты отдельным переключателем по умолчанию: `"legacy_products": false`. Без
явного `true` бот отказывает в создании нового счёта, а `commerce_offers: []` выключает их
даже при `legacy_products: true`.
**Оплаченное не теряется.** Гейт закрывает только создание новых счетов: проверка оплаты,
выдача и reconcile уже оплаченных счетов работают всегда — в том числе без платёжного токена
и без ограничения по возрасту счёта. Выдача идемпотентна: повторная проверка не продлевает
безлимит второй раз и не начисляет ранговый бонус повторно. Статус `paid` отделён от факта
доставки (`delivered`), поэтому сбой записи ранга или безлимита больше не выдаётся за
«✅ уже активировано» — обязательство остаётся в БД и довыдаётся поллером. API-безлимит
обещается пользователю только после фактической записи в шлюз; пока ключ не выпущен,
обязательство хранится как `api_state='pending'`, закрывается автоматически, а ответ честно
говорит «включим после выпуска ключа».
**Enable-флагов у board и кошелька нет**: `community_board` и `account_balances` не
выключаются — board-маршруты отдаются, доступ ограничен auth/ban/admin-гейтами, выключаются — board-маршруты отдаются, доступ ограничен auth/ban/admin-гейтами,
а пустые офферы отключают только покупки, не чтение кошелька и grants. а пустые офферы и `legacy_products: false` отключают только продажи, не чтение кошелька
и grants.
**Grace-окно счёта (180 с).** Если `createInvoice` завершился неоднозначно (сбой сети), **Grace-окно счёта (180 с).** Если `createInvoice` завершился неоднозначно (сбой сети),
строка счёта остаётся `uncertain` без `provider_invoice_id`; повтор с тем же `request_id` строка счёта остаётся `uncertain` без `provider_invoice_id`; повтор с тем же `request_id`
в пределах окна возвращает retryable `503 invoice_unconfirmed`, а после окна — терминальный в пределах окна возвращает retryable `503 invoice_unconfirmed`, а после окна — терминальный
+2 -1
View File
@@ -21,5 +21,6 @@
"cryptopay_token": "", "cryptopay_token": "",
"xrocket_token": "", "xrocket_token": "",
"sticker_packs": [], "sticker_packs": [],
"commerce_offers": [] "commerce_offers": [],
"legacy_products": false
} }
+763 -139
View File
File diff suppressed because it is too large Load Diff
+65 -2
View File
@@ -8,7 +8,70 @@ _log = logging.getLogger("gwerr")
import os as _os import os as _os
import sqlite3 as _sq import sqlite3 as _sq
_NEWAPI_DB = _os.environ.get("GW_NEWAPI_DB", "/opt/grok-gateway/new-api/one-api.db")
def _load_runtime_config():
"""runtime_config is the single source of truth for the effective paths.
Importing it directly works for both real entrypoints; the file-based fallback keeps
gateway-only importers (and tests) from silently reverting to the legacy literal.
"""
try:
import runtime_config
return runtime_config
except ImportError:
pass
candidate = _os.path.join(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))),
"bot", "runtime_config.py")
try:
import importlib.util as _iu
spec = _iu.spec_from_file_location("iishko_gateway_runtime_config", candidate)
if spec is None or spec.loader is None:
return None
module = _iu.module_from_spec(spec)
spec.loader.exec_module(module)
return module
except Exception:
return None
_runtime_config = _load_runtime_config()
_gateway_db_path = getattr(_runtime_config, "gateway_db_path", None)
_bot_config_path = getattr(_runtime_config, "bot_config_path", None)
_LEGACY_NEWAPI_DB = "/opt/grok-gateway/new-api/one-api.db"
def _config_newapi_db():
"""`newapi_db` from the bot config file, or "" when it names none.
The skin resolves its gateway DB through effective_bot_config(), so a deployment
that sets the path only in bot/config.json must not leave 401 diagnostics reading
the legacy literal. An unreadable or malformed file means "no opinion": env aliases
and the legacy default still apply.
"""
if _bot_config_path is None:
return ""
try:
with open(_bot_config_path(), encoding="utf-8-sig") as fh:
cfg = json.load(fh)
except Exception:
return ""
value = cfg.get("newapi_db") if isinstance(cfg, dict) else None
value = str(value).strip() if value else ""
return value
def _newapi_db():
"""Effective gateway DB, resolved late on every call.
Order: IISHKO_GW_DB > GATE_NEWAPI_DB (the shared resolver used by the skin, bot and
launcher) > GW_NEWAPI_DB (legacy units) > bot/config.json `newapi_db` (the value the
skin itself serves) > legacy literal. Previously this read a hardcoded legacy path
even when the process served a different effective database, so 401 diagnostics
classified keys against the wrong token table.
"""
legacy = _os.environ.get("GW_NEWAPI_DB") or _config_newapi_db() or _LEGACY_NEWAPI_DB
return _gateway_db_path(legacy) if _gateway_db_path else legacy
# [POLICYMSG 2810] Вердикт модерации апстрима детерминирован: тот же текст на том же # [POLICYMSG 2810] Вердикт модерации апстрима детерминирован: тот же текст на том же
# OpenAI «content_filter»). Прежняя формулировка «Повтори попытку или выбери другую # OpenAI «content_filter»). Прежняя формулировка «Повтори попытку или выбери другую
@@ -42,7 +105,7 @@ def token_state(api_key):
if not api_key: if not api_key:
return None return None
try: try:
con = _sq.connect("file:" + _NEWAPI_DB + "?mode=ro", uri=True, timeout=3) con = _sq.connect("file:" + _newapi_db() + "?mode=ro", uri=True, timeout=3)
try: try:
row = con.execute( row = con.execute(
'SELECT status, COALESCE(remain_quota,0), COALESCE(unlimited_quota,0) ' 'SELECT status, COALESCE(remain_quota,0), COALESCE(unlimited_quota,0) '
+170 -41
View File
@@ -527,35 +527,104 @@ PRICING_SHOWCASE = frozenset([
]) ])
# [PRICING-ALL 2026-10-20] витрина = ВСЕ живые модели шлюза (abilities enabled=1 # [PRICING-ALL 2026-10-20] витрина = ВСЕ живые модели шлюза (abilities enabled=1
import sqlite3 as _sqlite3, threading as _threading import threading as _threading
_LIVE_DB = "/opt/grok-gateway/new-api/one-api.db" # [CATALOGUE-DB 2026-10-31] Витрина читает ту же БД, что и шлюз. Жёсткий литерал
_live_lock = _threading.Lock() # игнорировал env-переопределение (IISHKO_GW_DB/GATE_NEWAPI_DB) и показывал модели
_live_cache = {"ts": 0.0, "models": set()} # из посторонней/мёртвой базы, поэтому берём эффективный путь.
_LIVE_DB = GATE_NEWAPI_DB
_LIVE_TTL = 300.0 # успешный снимок (в том числе честно пустой) живёт 5 минут
_LIVE_RETRY = 30.0 # после сбоя БД не перечитываем её на каждом запросе
_LIVE_MAX_STALE = _LIVE_TTL + _LIVE_RETRY
_live_lock = _threading.Lock() # защищает только _live_cache
_live_fetch_lock = _threading.Lock() # single-flight: один читатель БД за раз
_live_cache = {"ts": 0.0, "models": frozenset(), "known": False, "err_ts": None}
EXTRA_HIDE = frozenset({ EXTRA_HIDE = frozenset({
"", " ", "all", "codex-auto-review", "", " ", "all", "codex-auto-review",
}) # [ALLMODELS 20.10] витрина = ВСЕ живые модели; скрыт только мусор }) # [ALLMODELS 20.10] витрина = ВСЕ живые модели; скрыт только мусор
def get_live_models(): def _live_now():
import time as _t """Indirection over monotonic clock so tests can drive TTL/retry without sleeping."""
with _live_lock: return time.monotonic()
if _t.time() - _live_cache["ts"] < 300 and _live_cache["models"]:
return _live_cache["models"] def _live_read():
"""Живые модели из БД шлюза: строго read-only и без создания файла базы."""
con = sqlite3.connect(Path(_LIVE_DB).resolve().as_uri() + "?mode=ro", uri=True, timeout=5)
try: try:
con = _sqlite3.connect(_LIVE_DB, timeout=5)
con.execute("PRAGMA busy_timeout=5000") con.execute("PRAGMA busy_timeout=5000")
con.execute("PRAGMA query_only=ON")
rows = con.execute( rows = con.execute(
"SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id " "SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id "
"WHERE a.enabled=1 AND c.status=1").fetchall() "WHERE a.enabled=1 AND c.status=1").fetchall()
finally:
con.close() con.close()
models = {r[0] for r in rows if r[0] and r[0].strip()} return frozenset(str(r[0]) for r in rows if r[0] and str(r[0]).strip())
if models:
def _live_cached():
"""A failed database cannot make an old availability snapshot permanent."""
with _live_lock: with _live_lock:
_live_cache["ts"] = _t.time(); _live_cache["models"] = models if _live_cache["known"] and _live_now() - _live_cache["ts"] < _LIVE_MAX_STALE:
return models return _live_cache["models"], True
except Exception: return frozenset(), False
LOG.warning("live_models_db_fail", exc_info=True)
def _live_note_failure(exc):
"""Логируем сбой не чаще окна ретрая, и никогда не роняем запрос каталога."""
now = _live_now()
with _live_lock: with _live_lock:
return _live_cache["models"] quiet = _live_cache["err_ts"] is not None and now - _live_cache["err_ts"] < _LIVE_RETRY
_live_cache["err_ts"] = now
known = _live_cache["known"] and now - _live_cache["ts"] < _LIVE_MAX_STALE
cached = len(_live_cache["models"])
if quiet:
return
# sqlite_errorname (3.11+) names the reason without leaking the DB path.
reason = getattr(exc, "sqlite_errorname", "") or ""
label = "%s/%s" % (type(exc).__name__, reason) if reason else type(exc).__name__
if known:
LOG.warning("live_models_db_fail: %s — serving stale live set of %d models",
label, cached)
else:
LOG.warning("live_models_db_fail: %s — live set unknown, catalogue fail-closed",
label)
def _live_snapshot():
"""(models, known). known=False значит «набор живых моделей неизвестен», а не «живут все»."""
now = _live_now()
with _live_lock:
models, known = _live_cache["models"], _live_cache["known"]
ts, err_ts = _live_cache["ts"], _live_cache["err_ts"]
if known and now - ts < _LIVE_TTL:
return models, True
if err_ts is not None and now - err_ts < _LIVE_RETRY:
return _live_cached()
# Известный снимок отдаём сразу (stale-on-error), не встаём в очередь за обновлением.
if not _live_fetch_lock.acquire(blocking=not known):
return _live_cached()
try:
now = _live_now()
with _live_lock: # снимок мог обновить поток, державший лок до нас
if _live_cache["known"] and now - _live_cache["ts"] < _LIVE_TTL:
return _live_cache["models"], True
quiet = _live_cache["err_ts"] is not None and now - _live_cache["err_ts"] < _LIVE_RETRY
if quiet:
return _live_cached()
try:
models = _live_read()
except Exception as exc:
_live_note_failure(exc)
return _live_cached()
with _live_lock:
_live_cache.update(ts=_live_now(), models=models, known=True, err_ts=None)
return models, True
finally:
_live_fetch_lock.release()
def live_models_snapshot():
"""(models, known) для каталога: пустой known-набор честно пуст, неизвестный — fail-closed."""
return _live_snapshot()
def get_live_models():
"""Живые модели шлюза; неизменяемый набор, пустой при неизвестном состоянии БД."""
return _live_snapshot()[0]
def _hidden(nm): def _hidden(nm):
if nm in HIDE_MODEL_NAMES or nm in EXTRA_HIDE: if nm in HIDE_MODEL_NAMES or nm in EXTRA_HIDE:
@@ -581,22 +650,32 @@ def filter_pricing_body(raw):
if '/' in s: if '/' in s:
s = s.rsplit('/', 1)[-1] s = s.rsplit('/', 1)[-1]
return s.replace('-', '.') return s.replace('-', '.')
_cand = {} live, known = live_models_snapshot()
for r in rows: # [CATALOGUE-DB 2026-10-31] сначала скрытие и проверка живости, только потом
if isinstance(r, dict) and r.get('model_name') is not None: # дедуп: иначе победителем алиаса становится выключенная строка, и живая
_cand.setdefault(_norm_key(r['model_name']), []).append(str(r['model_name'])) # модель (например qwen-max) выпадает из каталога.
_best = {k: min(v, key=lambda n: (0 if '.' in n else 1, 0 if n == n.lower() else 1, len(n))) survivors = []
for k, v in _cand.items()}
live = get_live_models()
for row in rows: for row in rows:
if isinstance(row, dict): if isinstance(row, dict):
nm = row.get('model_name') nm = row.get('model_name')
if _hidden(nm): if _hidden(nm):
changed = True changed = True
continue continue
if live and nm not in live: if not known or nm not in live:
# known=False: состав живых моделей неизвестен — не выдумываем
# доступность. known=True и nm не в live: модель выключена.
changed = True changed = True
continue continue
survivors.append(row)
_cand = {}
for r in survivors:
if isinstance(r, dict) and r.get('model_name') is not None:
_cand.setdefault(_norm_key(r['model_name']), []).append(str(r['model_name']))
_best = {k: min(v, key=lambda n: (0 if '.' in n else 1, 0 if n == n.lower() else 1, len(n)))
for k, v in _cand.items()}
for row in survivors:
if isinstance(row, dict):
nm = row.get('model_name')
if _best.get(_norm_key(nm)) != str(nm): if _best.get(_norm_key(nm)) != str(nm):
changed = True changed = True
continue continue
@@ -628,7 +707,12 @@ def filter_pricing_body(raw):
for f_ in ("model_ratio", "model_price"): for f_ in ("model_ratio", "model_price"):
v = row.get(f_) v = row.get(f_)
if isinstance(v, (int, float)) and v: if isinstance(v, (int, float)) and v:
row[f_] = round(v / 2, 6) halved = round(v / 2, 6)
# [PRICING-PASS 2026-10-31] помечаем изменение только когда
# тариф действительно переписан: иначе любое тело с dict-строкой
# ре-сериализуется, хотя фильтр ничего не сделал.
if row.get(f_) != halved:
row[f_] = halved
changed = True changed = True
if not changed: if not changed:
return raw return raw
@@ -646,7 +730,8 @@ def response_headers(headers):
def error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None): def _error_payload(status, raw, path, user_balance=None, from_upstream=False, api_key=None):
"""Build the public error body. A 401 lookup touches the gateway SQLite DB."""
upstream_status = status upstream_status = status
status, payload = public_error(status, raw, path, user_balance=user_balance, status, payload = public_error(status, raw, path, user_balance=user_balance,
from_upstream=from_upstream, api_key=api_key) from_upstream=from_upstream, api_key=api_key)
@@ -655,12 +740,39 @@ def error_response(status, raw, path, headers=None, user_balance=None, from_upst
payload["error"].setdefault("request_id", request_id) payload["error"].setdefault("request_id", request_id)
LOG.warning("client_error status=%s upstream_status=%s code=%s path=%s request_id=%s", LOG.warning("client_error status=%s upstream_status=%s code=%s path=%s request_id=%s",
status, upstream_status, payload["error"]["code"], path, request_id) status, upstream_status, payload["error"]["code"], path, request_id)
return status, payload, request_id
def _finish_error(status, payload, request_id, headers=None):
safe_headers = CIMultiDict((k, v) for k, v in (headers or {}).items() safe_headers = CIMultiDict((k, v) for k, v in (headers or {}).items()
if k.lower() == "retry-after") if k.lower() == "retry-after")
safe_headers["Cache-Control"] = "no-store" safe_headers["Cache-Control"] = "no-store"
safe_headers["X-Request-ID"] = request_id safe_headers["X-Request-ID"] = request_id
return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps) return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps)
def error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None):
"""Synchronous wire form. Loop callers must use async_error_response()."""
return _finish_error(*_error_payload(status, raw, path, user_balance=user_balance,
from_upstream=from_upstream, api_key=api_key), headers=headers)
async def async_error_response(status, raw, path, headers=None, user_balance=None, from_upstream=False, api_key=None):
"""Same wire form as error_response(), with the DB lookup off the event loop.
Only a 401 classification reads the gateway SQLite token table, so other
statuses stay inline: during an upstream 5xx storm every reply would otherwise
pay an extra worker hop for nothing.
"""
if status == 401:
payload = await asyncio.to_thread(_error_payload, status, raw, path,
user_balance=user_balance, from_upstream=from_upstream,
api_key=api_key)
else:
payload = _error_payload(status, raw, path, user_balance=user_balance,
from_upstream=from_upstream, api_key=api_key)
return _finish_error(*payload, headers=headers)
def map_sse_frame(frame: bytes, path: str) -> bytes: def map_sse_frame(frame: bytes, path: str) -> bytes:
"""Pass through byte-exact; if a data: frame contains JSON {"error":...} -> map to event: error.""" """Pass through byte-exact; if a data: frame contains JSON {"error":...} -> map to event: error."""
if len(frame) > MAX_SSE_FRAME: if len(frame) > MAX_SSE_FRAME:
@@ -735,7 +847,7 @@ async def relay(req, upstream):
if (req.method == "GET" and req.path == "/api/pricing" and upstream.status == 200 if (req.method == "GET" and req.path == "/api/pricing" and upstream.status == 200
and "json" in upstream.headers.get("Content-Type", "").lower()): and "json" in upstream.headers.get("Content-Type", "").lower()):
raw = await upstream.read() raw = await upstream.read()
filtered = filter_pricing_body(raw) filtered = await asyncio.to_thread(filter_pricing_body, raw)
if filtered is not raw: if filtered is not raw:
LOG.info("pricing_dedup %d -> %d bytes", len(raw), len(filtered)) LOG.info("pricing_dedup %d -> %d bytes", len(raw), len(filtered))
return web.Response(status=upstream.status, body=filtered, headers=headers) return web.Response(status=upstream.status, body=filtered, headers=headers)
@@ -914,7 +1026,7 @@ async def proxy(req):
LOG.warning("client_disconnect_read") LOG.warning("client_disconnect_read")
return web.Response(status=499) return web.Response(status=499)
except web.HTTPException as exc: except web.HTTPException as exc:
return error_response(exc.status, b"", req.path, api_key=key_from_headers(req.headers)) return await async_error_response(exc.status, b"", req.path, api_key=key_from_headers(req.headers))
requested_model = None requested_model = None
request_object = None request_object = None
if is_api and body: if is_api and body:
@@ -1029,7 +1141,7 @@ async def proxy(req):
async def selected_failure(status, raw, outgoing): async def selected_failure(status, raw, outgoing):
key = key_from_headers(headers) key = key_from_headers(headers)
balance = await asyncio.to_thread(_key_balance_usd, key) balance = await asyncio.to_thread(_key_balance_usd, key)
return error_response(status, raw, req.path, headers=outgoing, return await async_error_response(status, raw, req.path, headers=outgoing,
user_balance=balance, from_upstream=True, api_key=key) user_balance=balance, from_upstream=True, api_key=key)
try: try:
return await relay_selected(req, session, URL(UPSTREAM + req.raw_path, encoded=True), return await relay_selected(req, session, URL(UPSTREAM + req.raw_path, encoded=True),
@@ -1060,9 +1172,9 @@ async def proxy(req):
sse_include_usage=sse_include_usage) sse_include_usage=sse_include_usage)
return await relay(req, upstream) return await relay(req, upstream)
except asyncio.TimeoutError: except asyncio.TimeoutError:
return error_response(504, b"", req.path, api_key=key_from_headers(req.headers)) return await async_error_response(504, b"", req.path, api_key=key_from_headers(req.headers))
except aiohttp.ClientError: except aiohttp.ClientError:
return error_response(503, b"", req.path, api_key=key_from_headers(req.headers)) return await async_error_response(503, b"", req.path, api_key=key_from_headers(req.headers))
# ---------- [BRAND] custom logo/favicon replaces new-api defaults (owner, 2026-10-11) ---------- # ---------- [BRAND] custom logo/favicon replaces new-api defaults (owner, 2026-10-11) ----------
@@ -1398,6 +1510,27 @@ def _tg_store_conn():
return con return con
def _tg_store_password(tg_id):
"""Stored password, with the connection closed before any network await."""
con = _tg_store_conn()
try:
row = con.execute("SELECT password FROM tg_users WHERE tg_id=?", (tg_id,)).fetchone()
return row[0] if row else None
finally:
con.close()
def _tg_store_password_put(tg_id, username, password):
"""Persist the provisioned password in its own short write transaction."""
con = _tg_store_conn()
try:
con.execute("INSERT OR REPLACE INTO tg_users(tg_id, username, password, created)"
" VALUES(?,?,?,?)", (tg_id, username, password, int(time.time())))
con.commit()
finally:
con.close()
def _key_share_seize(user_id, attacker_name, owner_name, key): def _key_share_seize(user_id, attacker_name, owner_name, key):
if attacker_name == owner_name: if attacker_name == owner_name:
return 0 # same identity: no violation to punish (defensive) return 0 # same identity: no violation to punish (defensive)
@@ -1802,10 +1935,10 @@ async def tg_login(req):
LOG.error("tg_login_admin_token_unreadable") LOG.error("tg_login_admin_token_unreadable")
return web.json_response({"success": False, "error": "provision_unavailable"}, status=500) return web.json_response({"success": False, "error": "provision_unavailable"}, status=500)
try: try:
con = _tg_store_conn() # Read the store in a worker and close it before provisioning: the previous
try: # version ran connect+schema DDL (with a 2s busy timeout) on the event loop and
row = con.execute("SELECT password FROM tg_users WHERE tg_id=?", (tg_id,)).fetchone() # kept the connection open across up to four network round trips.
password = row[0] if row else None password = await asyncio.to_thread(_tg_store_password, tg_id)
if password is None: if password is None:
password = secrets.token_urlsafe(24) password = secrets.token_urlsafe(24)
status, body, _ = await _newapi_call( status, body, _ = await _newapi_call(
@@ -1838,11 +1971,7 @@ async def tg_login(req):
LOG.warning("tg_login_recovery_put_failed uid=%s status=%s", uid, status) LOG.warning("tg_login_recovery_put_failed uid=%s status=%s", uid, status)
return web.json_response({"success": False, "error": "provision_failed"}, status=502) return web.json_response({"success": False, "error": "provision_failed"}, status=502)
LOG.info("tg_login_recovered uid=%s", uid) LOG.info("tg_login_recovered uid=%s", uid)
con.execute("INSERT OR REPLACE INTO tg_users(tg_id, username, password, created)" await asyncio.to_thread(_tg_store_password_put, tg_id, username, password)
" VALUES(?,?,?,?)", (tg_id, username, password, int(time.time())))
con.commit()
finally:
con.close()
await asyncio.to_thread(_tg_link_upsert, tg_id, username) await asyncio.to_thread(_tg_link_upsert, tg_id, username)
status, body, hdrs = await _newapi_call( status, body, hdrs = await _newapi_call(
session, "POST", "/api/user/login", None, session, "POST", "/api/user/login", None,
+17 -6
View File
@@ -38,6 +38,13 @@ _BUSY_PATHS = frozenset(("/v1/chat/completions", "/v1/completions",
_BUSY_WAITERS = WeakKeyDictionary() _BUSY_WAITERS = WeakKeyDictionary()
async def _upstream_error(status, raw, path, **context):
"""Keep the optional SQLite token lookup off the relay's event loop."""
if status == 401:
return await asyncio.to_thread(public_error, status, raw, path, **context)
return public_error(status, raw, path, **context)
class _BusyWaiters: class _BusyWaiters:
"""Single-loop recovery work, not generation/connection leases or an auth queue.""" """Single-loop recovery work, not generation/connection leases or an auth queue."""
@@ -428,8 +435,9 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non
raw = _decode(raw or b"", encoding) raw = _decode(raw or b"", encoding)
if len(raw) > MAX_ERROR_BODY: if len(raw) > MAX_ERROR_BODY:
raw = b"" raw = b""
status, payload = public_error(upstream.status, raw, request.path, status, payload = await _upstream_error(upstream.status, raw, request.path,
user_balance=user_balance, from_upstream=True, user_balance=user_balance,
from_upstream=True,
api_key=key_from_headers(request.headers)) api_key=key_from_headers(request.headers))
payload["error"]["gateway_request_id"] = request_id payload["error"]["gateway_request_id"] = request_id
safe_headers = {"X-Request-ID": request_id, "Cache-Control": "no-store"} safe_headers = {"X-Request-ID": request_id, "Cache-Control": "no-store"}
@@ -465,8 +473,10 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non
status = int(status) status = int(status)
except (ValueError, TypeError): except (ValueError, TypeError):
status = 502 status = 502
status, payload = public_error(status if 400 <= status <= 599 else 502, decoded, request.path, status, payload = await _upstream_error(status if 400 <= status <= 599 else 502,
user_balance=user_balance, from_upstream=True, decoded, request.path,
user_balance=user_balance,
from_upstream=True,
api_key=key_from_headers(request.headers)) api_key=key_from_headers(request.headers))
return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
try: try:
@@ -508,9 +518,10 @@ async def relay_api(request, upstream, *, user_balance=None, requested_model=Non
status = int(status) status = int(status)
except (ValueError, TypeError): except (ValueError, TypeError):
status = 502 status = 502
status, payload = public_error(status if 400 <= status <= 599 else 502, status, payload = await _upstream_error(status if 400 <= status <= 599 else 502,
_decode(raw, encoding), request.path, _decode(raw, encoding), request.path,
user_balance=user_balance, from_upstream=True, user_balance=user_balance,
from_upstream=True,
api_key=key_from_headers(request.headers)) api_key=key_from_headers(request.headers))
return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps) return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
except ModelIdentityError: except ModelIdentityError:
+71 -12
View File
@@ -2,17 +2,55 @@
import ast import ast
import asyncio import asyncio
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from pathlib import Path from pathlib import Path
import sqlite3 import sqlite3
import tempfile import tempfile
import threading import threading
import time import time
from types import SimpleNamespace
import unittest import unittest
from unittest import mock
from test_bot_stability import (BOT, Content, Response, Session, actual_gateway, from test_bot_stability import (BOT, Content, Response, Session, actual_gateway,
adapter, frame, stability) adapter, frame, stability)
class FakeClock:
"""Thread-safe monotonic clock that moves only when the test says so.
Budget accounting can then be asserted exactly instead of hoped for: no real
sleep, thread warm-up or scheduling delay can shorten the window.
"""
def __init__(self, start: float = 1000.0) -> None:
self.start = start
self._value = start
self._lock = threading.Lock()
def monotonic(self) -> float:
with self._lock:
return self._value
def advance(self, seconds: float) -> None:
with self._lock:
self._value += seconds
@contextmanager
def fake_timing(clock: FakeClock):
"""Drive adapter deadline math *and* event-loop timers from one fake clock.
The adapter reads ``bot_stability.time.monotonic``; the controller additionally
enforces its own deadline with ``loop.time()`` (``asyncio.timeout_at``). Both are
replaced, so expiry can only happen through ``clock.advance``.
"""
loop = asyncio.get_running_loop()
with mock.patch.object(adapter, "time", SimpleNamespace(monotonic=clock.monotonic)), \
mock.patch.object(loop, "time", clock.monotonic):
yield
class StreamEdges(unittest.IsolatedAsyncioTestCase): class StreamEdges(unittest.IsolatedAsyncioTestCase):
async def test_default_model_is_admitted_not_bypassed(self): async def test_default_model_is_admitted_not_bypassed(self):
session = Session([Response()]) session = Session([Response()])
@@ -229,23 +267,44 @@ class AdapterEdges(unittest.IsolatedAsyncioTestCase):
self.assertFalse(gate._cap_pending) self.assertFalse(gate._cap_pending)
async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self): async def test_remaining_budget_recomputed_after_cap_and_success_is_not_refunded(self):
calls = [] # The cap transaction consumes exactly half of the 125 ms budget, on a clock
# the test owns. A dispatch that kept the pre-cap budget (0.125) or that let
# real time eat the window cannot produce the asserted numbers.
budget, cap_cost = 0.125, 0.0625
clock = FakeClock()
dispatched, reserved, refunds = [], [], []
def reserve(uid, model): def reserve(uid, model):
time.sleep(.02) clock.advance(cap_cost)
reserved.append((uid, model))
return True, 1, 10, "receipt" return True, 1, 10, "receipt"
def release(key):
refunds.append(key)
return True
async def stream(messages, model, send, t=360, _deadline=None): async def stream(messages, model, send, t=360, _deadline=None):
calls.append(t) dispatched.append((model, t, _deadline))
self.assertLess(t, .07)
self.assertGreater(t, 0)
return "exact" 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")} ns = {"BOT_DB": "unused.db", "gw_chat_stream": stream,
gate = adapter.BotStability(ns); gate.install_wrappers() "pm_cap_reserve": reserve, "pm_cap_release": release}
token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, .08)) gate = adapter.BotStability(
try: self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact") ns, controller=stability.StabilityController(clock=clock.monotonic))
finally: adapter.POLICY.reset(token) gate.install_wrappers()
self.assertEqual(len(calls), 1) token = adapter.POLICY.set(adapter.RequestPolicy(7, 0, budget))
try:
with fake_timing(clock):
self.assertEqual(await ns["gw_chat_stream"]([], "m", None), "exact")
finally:
adapter.POLICY.reset(token)
gate._cap_executor.shutdown(wait=False)
self.assertEqual(reserved, [(7, "m")])
self.assertEqual(dispatched, [("m", budget - cap_cost, clock.start + budget)])
self.assertEqual(refunds, [])
self.assertFalse(gate._cleanup_tasks) self.assertFalse(gate._cleanup_tasks)
self.assertFalse(gate._cap_pending)
self.assertEqual(gate.controller.snapshot()["outcomes"]["success"], 1)
async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self): async def test_auxiliary_call_keeps_its_shorter_explicit_timeout(self):
calls = [] calls = []
+105
View File
@@ -2,8 +2,12 @@
import ast import ast
import importlib.util import importlib.util
import json import json
import os
from contextlib import closing
from pathlib import Path from pathlib import Path
import re import re
import sqlite3
import tempfile
import unittest import unittest
SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py' SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py'
@@ -294,5 +298,106 @@ class PolicyCodeClassificationTests(unittest.TestCase):
self.assertEqual((status, body['error']['code']), (400, 'invalid_request')) self.assertEqual((status, body['error']['code']), (400, 'invalid_request'))
class TokenStateDatabaseTests(unittest.TestCase):
"""A 401 diagnostic must read the effective gateway DB, not a legacy literal."""
ENV = ("GW_NEWAPI_DB", "IISHKO_GW_DB", "GATE_NEWAPI_DB", "GROK_BOT_CFG")
def setUp(self):
self._saved = {name: os.environ.get(name) for name in self.ENV}
for name in self.ENV:
os.environ.pop(name, None)
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.dir = tmp.name
def tearDown(self):
for name, value in self._saved.items():
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
def db(self, name, rows):
path = os.path.join(self.dir, name)
with closing(sqlite3.connect(path)) as con:
con.execute('CREATE TABLE tokens(id INTEGER PRIMARY KEY, "key" TEXT, status INTEGER,'
' remain_quota INTEGER, unlimited_quota INTEGER, deleted_at INTEGER)')
con.executemany('INSERT INTO tokens("key", status, remain_quota, unlimited_quota,'
' deleted_at) VALUES(?,?,?,?,?)', rows)
con.commit()
return path
def auth_error(self, key):
return MOD.public_error(401, b'{"error":{"message":"Invalid token"}}',
'/v1/chat/completions', api_key=key)
def write_config(self, newapi_db):
path = os.path.join(self.dir, 'config.json')
with open(path, 'w', encoding='utf-8-sig') as fh:
json.dump({'newapi_db': newapi_db, 'bot_token': 'x'}, fh)
os.environ['GROK_BOT_CFG'] = path
return path
def test_shared_resolver_is_wired_and_resolves_late(self):
self.assertIsNotNone(MOD._gateway_db_path,
'gateway_errors fell back to the hardcoded legacy DB path')
# behaviour, not module shape: an alias set after import must be honoured,
# which an import-time snapshot could never do
late = self.db('late.db', [('k', 1, 42, 0, None)])
os.environ['IISHKO_GW_DB'] = late
self.assertEqual(MOD.token_state('k'), (1, 42, 0))
def test_config_json_gateway_db_beats_the_legacy_literal(self):
"""A deployment that sets the path only in bot/config.json must not misread 401s."""
self.db('legacy.db', [('k', 4, 0, 0, None)])
configured = self.db('configured.db', [('k', 1, 7000, 0, None)])
self.write_config(configured)
self.assertEqual(MOD.token_state('k'), (1, 7000, 0))
# an explicit env alias still outvotes the config file
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('k', 2, 900, 0, None)])
self.assertEqual(MOD.token_state('k'), (2, 900, 0))
def test_missing_or_bogus_config_path_falls_back_without_raising(self):
os.environ['GROK_BOT_CFG'] = os.path.join(self.dir, 'no-such-dir', 'config.json')
self.assertIsNone(MOD.token_state('k'))
broken = os.path.join(self.dir, 'broken.json')
with open(broken, 'w', encoding='utf-8-sig') as fh:
fh.write('{"newapi_db": ')
os.environ['GROK_BOT_CFG'] = broken
self.assertIsNone(MOD.token_state('k'))
# a config that names a nonexistent DB is not an error either: no key state
self.write_config(os.path.join(self.dir, 'absent.db'))
self.assertIsNone(MOD.token_state('k'))
def test_env_precedence_decides_which_token_table_is_read(self):
stale = self.db('legacy.db', [('k', 4, 0, 0, None)])
live = self.db('effective.db', [('k', 1, 5000, 0, None)])
os.environ['GW_NEWAPI_DB'] = stale # legacy-only unit keeps working
self.assertEqual(MOD.token_state('k'), (4, 0, 0))
# a stale legacy alias must not outvote the DB the rest of the stack serves
os.environ['GATE_NEWAPI_DB'] = live
self.assertEqual(MOD.token_state('k'), (1, 5000, 0))
del os.environ['GATE_NEWAPI_DB']
self.assertEqual(MOD.token_state('k'), (4, 0, 0))
del os.environ['GW_NEWAPI_DB']
os.environ['GATE_NEWAPI_DB'] = stale
os.environ['IISHKO_GW_DB'] = live # canonical name wins over GATE_NEWAPI_DB
self.assertEqual(MOD.token_state('k'), (1, 5000, 0))
def test_zero_balance_key_is_reported_as_empty_not_invalid(self):
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('deadbeef', 1, 0, 0, None)])
status, body = self.auth_error('deadbeef')
self.assertEqual((status, body['error']['code']), (402, 'api_key_empty'))
def test_foreign_database_never_makes_a_healthy_key_look_empty(self):
# The old hardcoded path belonged to another deployment: a drained key there
# must not change this gateway's verdict about its own healthy key.
self.db('legacy.db', [('healthy', 4, 0, 0, None)])
os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('healthy', 1, 900000, 0, None)])
status, body = self.auth_error('healthy')
self.assertEqual((status, body['error']['code']), (401, 'invalid_api_key'))
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
+718
View File
@@ -0,0 +1,718 @@
"""Legacy rank/donation fulfillment: paid != delivered, honest API promises, opt-in sales.
The helpers live in the ``bot/grok_bot.py`` monolith, so the exact functions and module
constants are extracted by name and executed against disposable SQLite databases. Every
assertion below runs the real code: no source-string matching.
"""
import ast
import asyncio
import json
import os
import sqlite3
import sys
import tempfile
import threading
import time
import unittest
from contextlib import closing
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BOT_SRC = ROOT / "bot" / "grok_bot.py"
# _prem_api_unlim resolves the account's gateway key names through the real helper;
# a stub would let the tests pass while production mis-resolves token names.
sys.path.insert(0, str(ROOT / "bot"))
import account_limits # noqa: E402 (path prepared just above)
DONATION_FUNCS = (
"_prem_api_unlim", "_don_ensure_table", "_don_record_invoice", "_don_claim_paid",
"_don_fulfill", "_don_pending_api", "_don_reconcile", "_don_answer_text", "_don_confirm_text",
)
RANK_FUNCS = (
"_rb_ensure_table", "_rb_apply", "_rb_settle", "_rb_bonus_settle", "_rb_bonus_grant",
"_rb_token_bonus", "_rb_token_name", "_rb_reconcile", "_rb_claim_paid", "_rb_bonus_granted",
"_rb_pending_load", "_rb_pending_save", "_rb_pending_flush",
"_rb_delivered", "_rb_invoice_delivered",
"rankbuy_poll_loop",
)
GATE_FUNCS = ("_legacy_sales_enabled", "_legacy_gate_text")
CONSTS = ("_LEGACY_ON", "_LEGACY_GATE_TEXT", "_LEGACY_GATE_LOG")
USERS_DDL = ("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, token_name TEXT, banned INTEGER DEFAULT 0,"
" api_blocked INTEGER DEFAULT 0, unlim_until INTEGER DEFAULT 0,"
" badge_lock INTEGER DEFAULT 0, badge_until INTEGER DEFAULT 0)")
TOKENS_DDL = ('CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT, remain_quota INTEGER DEFAULT 0,'
' unlimited_quota INTEGER DEFAULT 0, status INTEGER DEFAULT 1, deleted_at INTEGER,'
' "group" TEXT DEFAULT \'t1\')')
LOYALTY_BONUS = {2: 500000, 3: 1000000, 4: 2500000}
class _Log:
def __init__(self):
self.lines = []
def _add(self, level, msg, args):
self.lines.append((level, (msg % args) if args else str(msg)))
def info(self, msg, *a):
self._add("info", msg, a)
def warning(self, msg, *a):
self._add("warning", msg, a)
def error(self, msg, *a):
self._add("error", msg, a)
def _extract(names, consts):
tree = ast.parse(BOT_SRC.read_text(encoding="utf-8"))
wanted, got = [], set()
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names:
wanted.append(node)
got.add(node.name)
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in consts:
wanted.append(node)
got.add(target.id)
missing = (set(names) | set(consts)) - got
if missing:
raise AssertionError(f"bot/grok_bot.py no longer defines: {sorted(missing)}")
return wanted
class LegacyFulfillmentCase(unittest.TestCase):
cryptopay_token = ""
xrocket_token = ""
commerce_offers = None
legacy_products = None
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.dir = Path(temp.name)
self.bot_db = str(self.dir / "bot.db")
self.gw_db = str(self.dir / "api.db")
self.log = _Log()
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute(USERS_DDL)
con.execute("INSERT INTO users(tg_id, token_name) VALUES(123, 'tg123')")
con.commit()
with closing(sqlite3.connect(self.gw_db)) as con:
con.execute(TOKENS_DDL)
con.commit()
cfg = {"newapi_db": self.gw_db, "bot_db": self.bot_db}
if self.commerce_offers is not None:
cfg["commerce_offers"] = self.commerce_offers
if self.legacy_products is not None:
cfg["legacy_products"] = self.legacy_products
self.ns = {
"sqlite3": sqlite3, "time": time, "json": json, "os": os, "Path": Path,
"account_limits": account_limits,
"log": self.log, "BOT_DB": self.bot_db, "GW_DB": self.gw_db, "CFG": cfg,
"CRYPTOPAY_TOKEN": self.cryptopay_token, "XROCKET_TOKEN": self.xrocket_token,
"LOYALTY_BONUS": LOYALTY_BONUS, "RANKBUY_PRICE": 10,
"RANKBUY_JUMP": {1: 25, 2: 18, 3: 10},
"capped_bonus": lambda uid, bonus: bonus,
"_RANK_SYNC": {}, "sync_rank_limits": lambda uid, ttl=0: None,
"_RB_PENDING_PATH": str(self.dir / "rb_pending_bonus.json"),
# rankbuy_poll_loop is extracted for the race tests: its `bot: Bot`
# annotation is evaluated at exec time.
"Bot": object, "asyncio": asyncio,
}
body = _extract(DONATION_FUNCS + RANK_FUNCS + GATE_FUNCS, CONSTS)
exec(compile(ast.Module(body=body, type_ignores=[]), "legacy-fulfillment", "exec"), self.ns)
# ── helpers ────────────────────────────────────────────────────────────
def call(self, name, *args):
return self.ns[name](*args)
def bot_sql(self, query, params=()):
with closing(sqlite3.connect(self.bot_db)) as con:
rows = con.execute(query, params).fetchall()
con.commit()
return rows
def gw_sql(self, query, params=()):
with closing(sqlite3.connect(self.gw_db)) as con:
rows = con.execute(query, params).fetchall()
con.commit()
return rows
def add_token(self, name="tg123", deleted_at=None, remain_quota=0, unlimited=0):
with closing(sqlite3.connect(self.gw_db)) as con:
con.execute("INSERT INTO tokens(name, remain_quota, unlimited_quota, deleted_at)"
" VALUES(?,?,?,?)", (name, remain_quota, unlimited, deleted_at))
con.commit()
def paid_donation(self, inv_id, uid=123, hours=24):
self.call("_don_record_invoice", inv_id, uid, hours)
self.assertTrue(self.call("_don_claim_paid", inv_id))
def paid_rank(self, inv_id, uid=123, to_lvl=2, amount="10", provider="cp"):
self.call("_rb_ensure_table")
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd,"
" status, created, provider) VALUES(?,?,?,?,?, 'paid', ?, ?)",
(inv_id, uid, to_lvl - 1, to_lvl, amount, int(time.time()) - 60, provider))
con.commit()
class DonationFulfillmentTests(LegacyFulfillmentCase):
def test_paid_donation_without_issued_key_keeps_api_obligation_pending(self):
"""No gateway token yet: premium is issued, the API promise stays pending and honest."""
self.paid_donation(9001)
before = int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0])
self.assertEqual(before, 0)
started = int(time.time())
res = self.call("_don_fulfill", 9001)
self.assertEqual(res["status"], "pending_api")
self.assertFalse(res["api"])
self.assertTrue(res["fresh"])
# premium starts at payment time, never at the epoch, and is not shortened
self.assertGreaterEqual(int(res["until"]), started + 24 * 3600)
self.assertLess(int(res["until"]), started + 24 * 3600 + 120)
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0],
int(res["until"]))
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')"
" FROM donations WHERE invoice_id=9001")[0],
("paid", 1, "pending"))
# the answer must not claim an API key that does not exist
answer = self.call("_don_answer_text", 24, res)
self.assertIn("API-безлимит включим автоматически", answer)
self.assertNotIn("и API-ключ", answer)
self.assertLessEqual(len(answer), 200)
self.assertIn("не сгорит", self.call("_don_confirm_text", 24, res))
def test_pending_api_entitlement_is_granted_once_the_key_exists(self):
self.paid_donation(9001)
first = self.call("_don_fulfill", 9001)
until_after_first = int(first["until"])
self.add_token("tg123")
granted = self.call("_don_pending_api")
self.assertEqual(granted, [(123, 9001)])
self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0],
(1, "premium"))
# a retry neither re-grants nor extends the paid premium a second time
self.assertEqual(self.call("_don_pending_api"), [])
again = self.call("_don_fulfill", 9001)
self.assertEqual(again["status"], "already")
self.assertTrue(again["api"])
self.assertFalse(again["fresh"])
self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
until_after_first)
self.assertEqual(self.bot_sql("SELECT COALESCE(api_state,'none') FROM donations"
" WHERE invoice_id=9001")[0][0], "granted")
def test_premium_hours_are_never_credited_twice(self):
self.paid_donation(9002, hours=72)
self.add_token("tg123")
first = self.call("_don_fulfill", 9002)
second = self.call("_don_fulfill", 9002)
self.assertEqual(first["status"], "granted")
self.assertEqual(second["status"], "already")
self.assertEqual(int(first["until"]), int(second["until"]))
self.assertEqual(self.bot_sql("SELECT COALESCE(until_ts,0) FROM donations WHERE invoice_id=9002")[0][0],
int(first["until"]))
self.assertEqual(self.call("_don_reconcile"), [])
def test_blocked_account_keeps_the_payment_without_entitlement(self):
self.bot_sql("UPDATE users SET banned=1 WHERE tg_id=123")
self.paid_donation(9003)
res = self.call("_don_fulfill", 9003)
self.assertEqual(res["status"], "blocked")
self.assertTrue(res["fresh"])
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0)
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none')"
" FROM donations WHERE invoice_id=9003")[0], ("paid", 1, "blocked"))
self.add_token("tg123")
self.assertEqual(self.call("_don_pending_api"), [])
self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0)
# a second pass does not re-notify and does not issue anything
self.assertEqual(self.call("_don_fulfill", 9003)["status"], "blocked")
self.assertEqual(self.call("_don_reconcile"), [])
self.assertIn("ограничен", self.call("_don_answer_text", 24, res))
def test_reconcile_delivers_paid_rows_without_any_provider_token(self):
"""A crash between provider confirmation and delivery is recovered offline."""
self.call("_don_ensure_table")
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("INSERT INTO donations(invoice_id, uid, hours, status, created)"
" VALUES(9004, 123, 168, 'paid', ?)", (int(time.time()) - 999999,))
con.commit()
self.add_token("tg123")
rows = self.call("_don_reconcile")
self.assertEqual([r[:3] for r in rows], [(9004, 123, 168)])
self.assertEqual(rows[0][3]["status"], "granted")
self.assertGreater(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
int(time.time()))
self.assertEqual(self.call("_don_reconcile"), [])
def test_repeated_invoice_recording_preserves_delivery_state(self):
self.paid_donation(9005, hours=24)
self.add_token("tg123")
res = self.call("_don_fulfill", 9005)
until = int(res["until"])
self.call("_don_record_invoice", 9005, 123, 24)
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(api_state,'none'),"
" COALESCE(until_ts,0) FROM donations WHERE invoice_id=9005")[0],
("paid", 1, "granted", until))
self.assertEqual(int(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0]),
until)
self.assertEqual(self.call("_don_fulfill", 9005)["status"], "already")
def test_legacy_paid_history_is_not_regranted_by_the_migration(self):
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER, hours INTEGER,"
" status TEXT DEFAULT 'pending', created INTEGER)")
con.execute("INSERT INTO donations VALUES(9006, 123, 24, 'paid', 1700000000)")
con.execute("INSERT INTO donations VALUES(9007, 123, 24, 'pending', 1700000000)")
con.commit()
self.add_token("tg123")
self.call("_don_ensure_table")
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(api_state,'none')"
" FROM donations WHERE invoice_id=9006")[0], (1, "granted"))
self.assertEqual(self.bot_sql("SELECT COALESCE(unlim_until,0) FROM users WHERE tg_id=123")[0][0], 0)
self.assertEqual(self.gw_sql("SELECT unlimited_quota FROM tokens WHERE name='tg123'")[0][0], 0)
self.assertEqual(self.call("_don_reconcile"), [])
# an old pending invoice is still deliverable: the age filter never applied here
self.call("_don_claim_paid", 9007)
self.assertEqual(self.call("_don_fulfill", 9007)["status"], "granted")
def test_missing_gateway_database_is_reported_not_created(self):
self.ns["CFG"]["newapi_db"] = str(self.dir / "absent" / "one-api.db")
self.assertFalse(self.call("_prem_api_unlim", 123))
self.assertFalse((self.dir / "absent").exists())
self.assertTrue(any(level == "error" for level, _ in self.log.lines))
def test_api_unlim_tells_the_truth_about_deleted_and_live_tokens(self):
self.assertFalse(self.call("_prem_api_unlim", 123)) # no row at all
self.add_token("tg123", deleted_at=int(time.time()))
self.assertFalse(self.call("_prem_api_unlim", 123)) # soft-deleted row is not a grant
with closing(sqlite3.connect(self.gw_db)) as con:
con.execute("UPDATE tokens SET deleted_at=NULL WHERE name='tg123'")
con.commit()
self.assertTrue(self.call("_prem_api_unlim", 123))
self.assertEqual(self.gw_sql("SELECT unlimited_quota, \"group\" FROM tokens WHERE name='tg123'")[0],
(1, "premium"))
class RankFulfillmentTests(LegacyFulfillmentCase):
def test_failed_grant_is_never_reported_as_activated_and_retry_finishes_it(self):
self.paid_rank(7001, to_lvl=2)
self.add_token("tg123")
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users"
" BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END")
con.commit()
self.assertFalse(self.call("_rb_settle", 123, 2, 7001))
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0) FROM rank_purchases"
" WHERE invoice_id=7001")[0], ("paid", 0))
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 0)
# reconcile keeps retrying while the write fails, and reports nothing to the user
self.assertEqual(self.call("_rb_reconcile"), [])
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0)
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("DROP TRIGGER fail_grant")
con.commit()
rows = self.call("_rb_reconcile")
self.assertEqual([r[:3] for r in rows], [(123, 2, 7001)])
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
" FROM rank_purchases WHERE invoice_id=7001")[0], ("paid", 1, "granted"))
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
# exactly one delivery: no second badge write, no second bonus
self.assertEqual(self.call("_rb_reconcile"), [])
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
self.assertTrue(self.call("_rb_bonus_granted", 7001))
def test_bonus_obligation_survives_a_missing_then_deleted_token_row(self):
self.call("_rb_pending_save", {"123": LOYALTY_BONUS[3]})
self.assertEqual(self.call("_rb_pending_flush"), 0)
self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]})
self.add_token("tg123", deleted_at=int(time.time()))
self.assertEqual(self.call("_rb_pending_flush"), 0)
self.assertEqual(self.call("_rb_pending_load"), {"123": LOYALTY_BONUS[3]})
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0], 0)
with closing(sqlite3.connect(self.gw_db)) as con:
con.execute("UPDATE tokens SET deleted_at=NULL, remain_quota=10 WHERE name='tg123'")
con.commit()
self.assertEqual(self.call("_rb_pending_flush"), 1)
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[3])
self.assertFalse(os.path.exists(self.ns["_RB_PENDING_PATH"]))
self.assertEqual(self.call("_rb_pending_flush"), 0)
def test_bonus_quota_uses_max_semantics_and_never_accumulates(self):
"""A retry must not pay the rank bonus twice or shrink an already larger balance."""
self.add_token("tg123", remain_quota=0)
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
# a user who already has more quota keeps it
self.assertTrue(self.call("_rb_bonus_grant", 123, 10))
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
# a disabled token is re-enabled, a deleted one is never resurrected
with closing(sqlite3.connect(self.gw_db)) as con:
con.execute("UPDATE tokens SET status=4 WHERE name='tg123'")
con.commit()
self.assertTrue(self.call("_rb_bonus_grant", 123, LOYALTY_BONUS[2]))
self.assertEqual(self.gw_sql("SELECT status FROM tokens WHERE name='tg123'")[0][0], 1)
self.assertFalse(self.call("_rb_bonus_grant", 456, LOYALTY_BONUS[2]))
def test_button_delivery_wins_the_race_and_reconcile_stays_silent(self):
"""One invoice = one delivery and one notification, whoever gets there first."""
self.paid_rank(7003, to_lvl=2)
self.add_token("tg123")
self.assertTrue(self.call("_rb_settle", 123, 2, 7003, True))
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
" FROM rank_purchases WHERE invoice_id=7003")[0],
("paid", 1, "granted"))
# the poller re-reads the same invoice and must neither re-deliver nor announce it
self.assertEqual(self.call("_rb_reconcile"), [])
self.assertFalse(self.call("_rb_settle", 123, 2, 7003, True))
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
self.assertTrue(self.call("_rb_invoice_delivered", 7003))
self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines))
def test_poller_loses_the_button_race_and_does_not_confirm_twice(self):
"""The paid_list sweep must claim too: the button can deliver mid-sweep."""
self.call("_rb_ensure_table")
for inv in (7101, 7102):
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl,"
" amount_usd, status, created, provider)"
" VALUES(?, 123, 1, 2, '10', 'pending', ?, 'cp')",
(inv, int(time.time()) - 60))
con.commit()
self.add_token("tg123")
self.ns["CRYPTOPAY_TOKEN"] = "tok"
confirms = []
async def _rb_confirm(bot, uid, to_lvl, amount, provider, bonus_ok):
confirms.append((uid, to_lvl, amount, provider, bonus_ok))
async def _rb_inv_paid(provider, inv_id, inv_ext):
if int(inv_id) == 7102:
# the sweep is still polling: meanwhile the user pressed «Я оплатил» for 7101
# (status is already 'paid', delivered=0), which delivers and announces it.
if self.ns["_rb_settle"](123, 2, 7101, True):
await _rb_confirm(None, 123, 2, "10", "cp",
self.ns["_rb_bonus_granted"](7101))
return False
return True
class _Driver:
"""One poll pass, then cancellation instead of a real 15s sleep."""
CancelledError = asyncio.CancelledError
to_thread = staticmethod(asyncio.to_thread)
def __init__(self):
self.passes = 0
async def sleep(self, *_a):
self.passes += 1
if self.passes > 1:
raise asyncio.CancelledError
self.ns["_rb_confirm"] = _rb_confirm
self.ns["_rb_inv_paid"] = _rb_inv_paid
self.ns["asyncio"] = _Driver()
with self.assertRaises(asyncio.CancelledError):
asyncio.run(self.ns["rankbuy_poll_loop"](None))
# exactly one announcement: the button's. The poller re-settling 7101 must be silent.
self.assertEqual(confirms, [(123, 2, "10", "cp", True)])
self.assertEqual(self.bot_sql("SELECT status, COALESCE(delivered,0), COALESCE(bonus_state,'none')"
" FROM rank_purchases WHERE invoice_id=7101")[0],
("paid", 1, "granted"))
# MAX semantics: the second settle attempt must not double the bonus quota
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
self.assertIn("rankbuy already delivered", " ".join(line for _, line in self.log.lines))
def test_claim_rolls_back_when_the_grant_fails_so_retry_can_finish_it(self):
self.paid_rank(7004, to_lvl=2)
self.add_token("tg123")
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("CREATE TRIGGER fail_grant BEFORE UPDATE OF badge_lock ON users"
" BEGIN SELECT RAISE(ABORT, 'injected persistent grant write failure'); END")
con.commit()
self.assertFalse(self.call("_rb_settle", 123, 2, 7004, True))
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0), COALESCE(bonus_state,'none')"
" FROM rank_purchases WHERE invoice_id=7004")[0][0], 0)
self.assertFalse(self.call("_rb_invoice_delivered", 7004))
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("DROP TRIGGER fail_grant")
con.commit()
self.assertEqual([r[:3] for r in self.call("_rb_reconcile")], [(123, 2, 7004)])
self.assertTrue(self.call("_rb_invoice_delivered", 7004))
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
self.assertEqual(self.gw_sql("SELECT remain_quota FROM tokens WHERE name='tg123'")[0][0],
LOYALTY_BONUS[2])
def test_delivered_probe_reports_false_on_a_broken_database(self):
"""A dead DB must not turn into an exception on the callback path."""
self.call("_rb_ensure_table")
self.assertFalse(self.call("_rb_invoice_delivered", 9999))
self.ns["BOT_DB"] = str(self.dir / "no-such-dir" / "bot.db")
self.assertFalse(self.call("_rb_invoice_delivered", 9999))
self.assertTrue(any(line.startswith("rb delivered read") for _, line in self.log.lines))
def test_claim_paid_is_a_one_shot_transition(self):
self.call("_rb_ensure_table")
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute("INSERT INTO rank_purchases(invoice_id, uid, from_lvl, to_lvl, amount_usd,"
" status, created, provider) VALUES(7002, 123, 1, 2, '10', 'pending', ?, 'cp')",
(int(time.time()),))
con.commit()
self.assertTrue(self.call("_rb_claim_paid", 7002))
self.assertFalse(self.call("_rb_claim_paid", 7002))
self.assertEqual(self.bot_sql("SELECT status FROM rank_purchases WHERE invoice_id=7002")[0][0], "paid")
class LegacySalesGateTests(LegacyFulfillmentCase):
def test_empty_offer_list_is_a_hard_switch_even_with_opt_in(self):
self.ns["CFG"]["commerce_offers"] = []
self.ns["CFG"]["legacy_products"] = True
self.assertFalse(self.call("_legacy_sales_enabled"))
self.assertTrue(self.call("_legacy_gate_text", "donate"))
self.assertTrue(self.call("_legacy_gate_text", "rank"))
self.assertIn("[LEGACY-GATE]", "\n".join(m for _, m in self.log.lines))
def test_legacy_products_are_off_by_default(self):
self.ns["CFG"]["commerce_offers"] = [{"id": "x"}]
self.assertFalse(self.call("_legacy_sales_enabled"))
self.assertTrue(self.call("_legacy_gate_text", "donate"))
self.assertTrue(self.call("_legacy_gate_text", "unknown-kind"))
def test_explicit_opt_in_with_offers_reopens_sales(self):
self.ns["CFG"]["commerce_offers"] = [{"id": "x"}]
self.ns["CFG"]["legacy_products"] = "yes"
self.assertTrue(self.call("_legacy_sales_enabled"))
self.assertIsNone(self.call("_legacy_gate_text", "rank"))
def test_gate_blocks_new_invoices_but_never_strands_paid_money(self):
self.ns["CFG"]["commerce_offers"] = []
self.assertTrue(self.call("_legacy_gate_text", "donate"))
self.paid_donation(9100, hours=24)
res = self.call("_don_fulfill", 9100)
self.assertEqual(res["status"], "pending_api")
self.assertEqual(self.bot_sql("SELECT COALESCE(delivered,0) FROM donations WHERE invoice_id=9100")[0][0], 1)
self.paid_rank(7100, to_lvl=2)
self.assertTrue(self.call("_rb_settle", 123, 2, 7100))
self.assertEqual(self.bot_sql("SELECT COALESCE(badge_lock,0) FROM users WHERE tg_id=123")[0][0], 2)
class DonationCallbackContractTests(LegacyFulfillmentCase):
"""The button handler must answer honestly for every delivery outcome."""
def test_answer_texts_are_short_and_match_their_state(self):
cases = {
"granted": "✅ Прем на 24ч! Безлимит: чат, картинки и API-ключ",
"pending_api": "API-безлимит включим автоматически",
"blocked": "аккаунт ограничен",
"already": "Уже активировано",
"error": "Не удалось подтвердить",
}
for status, needle in cases.items():
text = self.call("_don_answer_text", 24, {"status": status, "until": 0, "api": False})
self.assertLessEqual(len(text), 200, status)
self.assertIn(needle, text)
def test_confirm_text_reports_the_real_deadline(self):
until = int(time.time()) + 3600
text = self.call("_don_confirm_text", 24, {"status": "granted", "until": until, "api": True})
self.assertIn(time.strftime("%d.%m %H:%M", time.localtime(until)), text)
self.assertIn("24ч", text)
self.assertIn("API-безлимит включён", text)
pending = self.call("_don_confirm_text", 24, {"status": "pending_api", "until": until, "api": False})
self.assertNotIn("API-безлимит включён", pending)
self.assertIn("как только выпустится твой ключ", pending)
def test_donation_payload_is_json_serialisable_for_the_ui(self):
self.paid_donation(9200)
res = self.call("_don_fulfill", 9200)
self.assertEqual(json.loads(json.dumps(res)), res)
class _PausingConnection:
"""Real sqlite3 connection whose schema probe can be frozen mid-transaction."""
def __init__(self, inner, on_pragma):
self._inner = inner
self._on_pragma = on_pragma
def __getattr__(self, name):
return getattr(self._inner, name)
@property
def isolation_level(self):
return self._inner.isolation_level
@isolation_level.setter
def isolation_level(self, value):
self._inner.isolation_level = value
def execute(self, sql, params=()):
if str(sql).lstrip().upper().startswith("PRAGMA TABLE_INFO"):
self._on_pragma()
return self._inner.execute(sql, params)
class _PausingSqlite3:
def __init__(self, real, on_pragma):
self._real = real
self._on_pragma = on_pragma
def __getattr__(self, name):
return getattr(self._real, name)
def connect(self, *args, **kwargs):
return _PausingConnection(self._real.connect(*args, **kwargs), self._on_pragma)
class MigrationWindowTests(LegacyFulfillmentCase):
"""The additive migration holds a write lock for its whole read-modify-write span.
A stale ``PRAGMA table_info`` snapshot is the classic money bug here: the caller that
read the old schema still runs the fresh-install backfill seconds later, and every
``status='paid' AND delivered=0`` row that landed in between is marked delivered
without ever being granted. Serialising the migration closes that window.
"""
def _assert_migration_blocks_concurrent_writes(self, ensure_fn, table, ddl, invoice):
paused, release = threading.Event(), threading.Event()
errors = []
with closing(sqlite3.connect(self.bot_db)) as con:
con.execute(ddl)
# already-paid history: the backfill must mark it delivered exactly once
con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)"
" VALUES(?, 123, 'paid', 1)", (invoice - 1,))
con.commit()
def migrate():
try:
self.call(ensure_fn)
except BaseException as exc: # reported on the main thread
errors.append(exc)
real_sqlite3 = self.ns["sqlite3"]
self.ns["sqlite3"] = _PausingSqlite3(
real_sqlite3, lambda: (paused.set(), release.wait(20)))
self.addCleanup(self.ns.__setitem__, "sqlite3", real_sqlite3)
migrator = threading.Thread(target=migrate, daemon=True)
migrator.start()
buyers = []
def _cleanup():
# registered before the temp-dir cleanup, so it always runs first: a failing
# assertion must not leave a thread holding the SQLite file open on Windows
release.set()
migrator.join(20)
for t in buyers:
t.join(20)
self.addCleanup(_cleanup)
self.assertTrue(paused.wait(20), f"{ensure_fn} never probed the schema")
# a brand-new purchase arrives while the migration is between probe and backfill
landed = threading.Event()
def buy():
try:
with closing(real_sqlite3.connect(self.bot_db, timeout=20)) as con:
con.execute(f"INSERT INTO {table}(invoice_id, uid, status, created)"
" VALUES(?, 123, 'paid', 2)", (invoice,))
con.commit()
landed.set()
except BaseException as exc:
errors.append(exc)
buyer = threading.Thread(target=buy, daemon=True)
buyers.append(buyer)
buyer.start()
buyer.join(4)
self.assertFalse(landed.is_set(),
f"{ensure_fn}: a paid invoice landed inside the migration window")
release.set()
migrator.join(20)
self.assertFalse(migrator.is_alive(), f"{ensure_fn} did not finish")
self.assertEqual(errors, [])
buyer.join(20)
self.assertTrue(landed.is_set(), "the new purchase never landed at all")
self.assertEqual(errors, [])
delivered = dict(self.bot_sql(f"SELECT invoice_id, COALESCE(delivered,0) FROM {table}"))
self.assertEqual(delivered[invoice - 1], 1,
"already-paid history must not be re-granted by the poller")
self.assertEqual(delivered[invoice], 0,
"the new purchase was marked delivered without being granted")
def test_rank_migration_holds_the_write_lock_until_the_backfill_committed(self):
self._assert_migration_blocks_concurrent_writes(
"_rb_ensure_table", "rank_purchases",
"CREATE TABLE rank_purchases(invoice_id INTEGER PRIMARY KEY, uid INTEGER,"
" from_lvl INTEGER, to_lvl INTEGER, amount_usd TEXT,"
" status TEXT DEFAULT 'pending', created INTEGER, provider TEXT DEFAULT 'cp')",
901)
def test_donation_migration_holds_the_write_lock_until_the_backfill_committed(self):
self._assert_migration_blocks_concurrent_writes(
"_don_ensure_table", "donations",
"CREATE TABLE donations(invoice_id INTEGER PRIMARY KEY, uid INTEGER,"
" hours INTEGER, status TEXT DEFAULT 'pending', created INTEGER)",
902)
def test_parallel_migrations_do_not_fail_on_a_duplicate_column(self):
"""Button and poller migrate at once: exactly one ALTER set wins, nobody raises."""
failures = []
start = threading.Barrier(6)
def migrate():
start.wait(10)
try:
self.call("_rb_ensure_table")
except BaseException as exc:
failures.append(repr(exc))
threads = [threading.Thread(target=migrate, daemon=True) for _ in range(6)]
for t in threads:
t.start()
for t in threads:
t.join(30)
self.assertFalse(t.is_alive(), "a migration thread hung")
self.assertEqual(failures, [])
cols = [r[1] for r in self.bot_sql("PRAGMA table_info(rank_purchases)")]
for expected in ("provider", "inv_ext", "delivered", "delivered_at",
"bonus_state", "bonus_due"):
self.assertEqual(cols.count(expected), 1, f"column {expected} malformed: {cols}")
if __name__ == "__main__":
unittest.main(verbosity=2)
+197
View File
@@ -0,0 +1,197 @@
"""A blocked token lookup must not stall unrelated relay work on the event loop."""
import ast
import asyncio
import importlib.util
import itertools
import json
import logging
from pathlib import Path
import sys
import threading
from types import SimpleNamespace
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'gateway'))
SPEC = importlib.util.spec_from_file_location('responsive_error_relay', ROOT / 'gateway/transparent_api.py')
if SPEC is None or SPEC.loader is None:
raise RuntimeError('Cannot load the relay under test')
RELAY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(RELAY)
SKIN = ROOT / 'gateway' / 'grok-web-skin.py'
SKIN_ERROR_FUNCS = ('_error_payload', '_finish_error', 'error_response', 'async_error_response')
_LOGGERS = itertools.count()
def _skin_error_ns():
"""Extract the real skin error-response functions (hyphenated module, import side effects)."""
from aiohttp import web
from multidict import CIMultiDict
import secrets
from gateway_errors import public_error, public_json_dumps
tree = ast.parse(SKIN.read_text(encoding='utf-8'))
found = {n.name: n for n in tree.body
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name in SKIN_ERROR_FUNCS}
missing = [name for name in SKIN_ERROR_FUNCS if name not in found]
if missing:
raise AssertionError('skin error-response region changed shape; missing %s' % missing)
log = logging.getLogger('skin-error-%d' % next(_LOGGERS))
log.setLevel(logging.CRITICAL)
log.propagate = False
ns = {'asyncio': asyncio, 'secrets': secrets, 'web': web, 'CIMultiDict': CIMultiDict,
'public_error': public_error, 'public_json_dumps': public_json_dumps, 'LOG': log}
for name in SKIN_ERROR_FUNCS:
exec(compile(ast.Module(body=[found[name]], type_ignores=[]), str(SKIN), 'exec'), ns)
return ns
class ErrorResponsivenessTests(unittest.IsolatedAsyncioTestCase):
async def exercise(self, *, embedded=False):
loop = asyncio.get_running_loop()
started = asyncio.Event()
release = threading.Event()
owner = threading.get_ident()
called = []
pending = None
def mapper(status, raw, path, **context):
called.append((status, raw, path, context, threading.get_ident()))
loop.call_soon_threadsafe(started.set)
if not release.wait(2):
raise AssertionError('lookup blocked the relay event loop')
return 401, {'error': {'code': 'invalid_api_key', 'retryable': False}}
class Content:
async def iter_chunked(self, size):
yield body
body = json.dumps({'error': {'status': 401, 'message': 'invalid token'}}).encode()
upstream = SimpleNamespace(status=200 if embedded else 401,
headers={'Content-Type': 'application/json'}, content=Content())
request = SimpleNamespace(path='/v1/chat/completions', headers={})
try:
with patch.object(RELAY, 'public_error', side_effect=mapper):
pending = asyncio.create_task(RELAY.relay_api(
request, upstream, json_to_sse=embedded, user_balance=7))
await asyncio.wait_for(started.wait(), 2)
# This coroutine runs while the mapper is still blocked in its worker.
self.assertFalse(pending.done())
self.assertNotEqual(called[0][-1], owner)
release.set()
response = await asyncio.wait_for(pending, 2)
finally:
release.set()
if pending is not None and not pending.done():
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2)
self.assertEqual(response.status, 401)
payload = json.loads(response.body)
self.assertEqual(payload['error']['code'], 'invalid_api_key')
self.assertFalse(payload['error']['retryable'])
self.assertEqual(len(called), 1)
self.assertEqual(called[0][0], 401)
self.assertEqual(called[0][1], body)
self.assertEqual(called[0][2], request.path)
self.assertEqual(called[0][3]['user_balance'], 7)
self.assertTrue(called[0][3]['from_upstream'])
return payload
async def test_http_401_token_lookup_does_not_stall_other_coroutines(self):
payload = await self.exercise()
self.assertTrue(payload['error']['gateway_request_id'])
async def test_embedded_401_uses_the_same_nonblocking_lookup(self):
await self.exercise(embedded=True)
async def test_other_statuses_keep_the_no_worker_fast_path(self):
result = (503, {'error': {'code': 'upstream_unavailable'}})
with patch.object(RELAY, 'public_error', return_value=result) as mapper:
with patch.object(RELAY.asyncio, 'to_thread', side_effect=AssertionError('unexpected worker')):
actual = await RELAY._upstream_error(503, b'{}', '/v1/chat/completions', user_balance=5)
self.assertIs(actual, result)
mapper.assert_called_once_with(503, b'{}', '/v1/chat/completions', user_balance=5)
class SkinErrorResponseTests(unittest.IsolatedAsyncioTestCase):
"""The skin shares the relay's rule: only a 401 pays for a worker hop."""
async def test_non_401_stays_inline_and_matches_the_sync_wire_form(self):
ns = _skin_error_ns()
owner = threading.get_ident()
threads = []
real_payload = ns['_error_payload']
def recording(*args, **kwargs):
out = real_payload(*args, **kwargs)
threads.append(threading.get_ident())
return out
ns['_error_payload'] = recording
with patch.object(asyncio, 'to_thread', side_effect=AssertionError('unexpected worker hop')):
response = await ns['async_error_response'](503, b'{}', '/v1/chat/completions')
self.assertEqual(threads, [owner])
self.assertEqual(response.status, 503)
payload = json.loads(response.body)
self.assertTrue(payload['error']['gateway_request_id'])
self.assertEqual(payload['error']['request_id'], payload['error']['gateway_request_id'])
self.assertEqual(response.headers['Cache-Control'], 'no-store')
self.assertEqual(response.headers['X-Request-ID'], payload['error']['gateway_request_id'])
# identical classification to the synchronous form, with a fresh request id
sync = json.loads(ns['error_response'](503, b'{}', '/v1/chat/completions').body)
self.assertEqual(payload['error']['code'], sync['error']['code'])
self.assertNotEqual(payload['error']['gateway_request_id'], sync['error']['gateway_request_id'])
async def test_401_token_lookup_leaves_the_skin_event_loop(self):
ns = _skin_error_ns()
loop = asyncio.get_running_loop()
owner = threading.get_ident()
started = asyncio.Event()
release = threading.Event()
threads = []
contexts = []
def mapper(status, raw, path, **context):
threads.append(threading.get_ident())
contexts.append(context)
loop.call_soon_threadsafe(started.set)
if not release.wait(2):
raise AssertionError('blocked lookup stalled the test')
return status, {'error': {'code': 'invalid_api_key', 'retryable': False}}
ns['public_error'] = mapper
ticks = 0
async def ticker():
nonlocal ticks
while ticks < 5:
ticks += 1
await asyncio.sleep(0)
pending = None
try:
pending = asyncio.create_task(ns['async_error_response'](
401, b'{}', '/v1/chat/completions', api_key='sk-under-test'))
await asyncio.wait_for(started.wait(), 2)
# unrelated coroutines keep running while the DB lookup is blocked
self.assertFalse(pending.done())
await asyncio.wait_for(ticker(), 2)
release.set()
response = await asyncio.wait_for(pending, 2)
finally:
release.set()
if pending is not None and not pending.done():
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 2)
self.assertNotEqual(threads, [owner])
self.assertEqual(ticks, 5)
self.assertEqual(contexts[0]['api_key'], 'sk-under-test')
self.assertEqual(response.status, 401)
payload = json.loads(response.body)
self.assertEqual(payload['error']['code'], 'invalid_api_key')
self.assertTrue(payload['error']['gateway_request_id'])
self.assertEqual(response.headers['Cache-Control'], 'no-store')
if __name__ == '__main__':
unittest.main()
+456
View File
@@ -0,0 +1,456 @@
"""Live-model catalogue of gateway/grok-web-skin.py: effective DB, cache, fail-closed.
These tests execute the real functions of the skin (top-level `ast` nodes) against a
real SQLite file, so DB path resolution, read-only access, caching, retry and alias
deduplication are exercised as behaviour rather than asserted against source text.
"""
import ast
import asyncio
import json
import logging
import sqlite3
import threading
import time
from pathlib import Path
from types import SimpleNamespace
from unittest import IsolatedAsyncioTestCase
from aiohttp import web
SKIN = Path(__file__).resolve().parents[1] / "gateway" / "grok-web-skin.py"
ASSIGNS = ("_LIVE_DB", "_LIVE_TTL", "_LIVE_RETRY", "_LIVE_MAX_STALE", "_live_lock", "_live_fetch_lock",
"_live_cache", "EXTRA_HIDE")
FUNCS = ("_live_now", "_live_read", "_live_cached", "_live_note_failure", "_live_snapshot",
"live_models_snapshot", "get_live_models", "_hidden", "filter_pricing_body")
_counter = iter(range(10000))
def _nodes():
tree = ast.parse(SKIN.read_text(encoding="utf-8"))
assigns, funcs = {}, {}
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
funcs[node.name] = node
elif isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in ASSIGNS:
assigns[target.id] = node
return assigns, funcs
def _logger(sink):
log = logging.getLogger("skin-catalogue-%d" % next(_counter))
log.setLevel(logging.WARNING)
log.propagate = False
handler = logging.Handler()
handler.emit = sink.append
log.addHandler(handler)
return log
def _ns(db_path, hide=()):
"""Namespace with the real catalogue assignments and functions of the skin."""
source = SKIN.read_text(encoding="utf-8")
assigns, funcs = _nodes()
missing = [n for n in ASSIGNS if n not in assigns] + [n for n in FUNCS if n not in funcs]
assert not missing, "catalogue region changed shape: missing %s" % missing
sink = []
ns = {
"json": json, "logging": logging, "time": time, "sqlite3": sqlite3,
"Path": Path, "_threading": threading,
"GATE_NEWAPI_DB": str(db_path),
"LOG": _logger(sink),
"HIDE_MODEL_NAMES": frozenset(hide),
"HIDDEN_GROUP": "vip",
"sink": sink,
"source": source,
}
for name in ASSIGNS:
exec(compile(ast.Module(body=[assigns[name]], type_ignores=[]), str(SKIN), "exec"), ns)
for name in FUNCS:
exec(compile(ast.Module(body=[funcs[name]], type_ignores=[]), str(SKIN), "exec"), ns)
return ns
def _make_db(path, live=(), disabled=()):
con = sqlite3.connect(path)
try:
con.execute("CREATE TABLE channels (id INTEGER PRIMARY KEY, status INTEGER NOT NULL)")
con.execute("CREATE TABLE abilities (id INTEGER PRIMARY KEY, model TEXT, channel_id INTEGER,"
" enabled INTEGER NOT NULL)")
con.execute("INSERT INTO channels (id, status) VALUES (1, 1), (2, 2)")
con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 1, 1)",
[(m,) for m in live])
con.executemany("INSERT INTO abilities (model, channel_id, enabled) VALUES (?, 2, 1)",
[(m,) for m in disabled])
con.commit()
finally:
con.close()
return path
def _pricing(*names, **extra):
rows = [{"model_name": name} for name in names]
body = {"object": "list", "data": rows}
body.update(extra)
return json.dumps(body).encode("utf-8")
def _kept(raw, ns):
filtered = ns["filter_pricing_body"](raw)
return [row["model_name"] for row in json.loads(filtered)["data"]]
def _counting_read(ns):
"""Replace the DB reader with a wrapper that records every real attempt."""
calls = []
real = ns["_live_read"]
def wrapped():
calls.append(1)
return real()
ns["_live_read"] = wrapped
return calls
# --- database selection ---------------------------------------------------------------
def test_catalogue_follows_the_supplied_gateway_db(tmp_path):
"""A hardcoded legacy path would ignore the effective DB, so both reads must differ."""
first = _make_db(tmp_path / "first.db", live=["grok-4.6"])
second = _make_db(tmp_path / "second.db", live=["grok-4.7"])
ns_a, ns_b = _ns(first), _ns(second)
assert ns_a["_LIVE_DB"] == str(first)
assert ns_b["_LIVE_DB"] == str(second)
assert ns_a["get_live_models"]() == frozenset({"grok-4.6"})
assert ns_b["get_live_models"]() == frozenset({"grok-4.7"})
def test_catalogue_reads_effective_db_not_legacy(tmp_path):
effective = _make_db(tmp_path / "effective.db", live=["grok-4.6"])
legacy = _make_db(tmp_path / "legacy.db", live=["legacy-only"])
ns = _ns(effective)
models = ns["get_live_models"]()
assert models == frozenset({"grok-4.6"})
assert ns["_LIVE_DB"] == str(effective)
assert ns["_LIVE_DB"] != str(legacy)
# the legacy file exists and holds other rows; none of them may surface
assert legacy.exists()
assert "legacy-only" not in models
def test_effective_env_path_overrides_config_file(tmp_path, monkeypatch):
"""Regression guard for the mismatch: env path wins over the config-file value."""
import runtime_config
configured = _make_db(tmp_path / "configured.db", live=["legacy-only"])
forced = _make_db(tmp_path / "forced.db", live=["grok-4.6"])
monkeypatch.setenv("IISHKO_GW_DB", str(forced))
monkeypatch.delenv("GATE_NEWAPI_DB", raising=False)
cfg = runtime_config.effective_bot_config({"newapi_db": str(configured)})
assert cfg["newapi_db"] == str(forced)
assert _ns(cfg["newapi_db"])["get_live_models"]() == frozenset({"grok-4.6"})
# --- read-only access ----------------------------------------------------------------
def test_missing_db_is_not_created_and_state_is_unknown(tmp_path):
missing = tmp_path / "absent.db"
ns = _ns(missing)
models, known = ns["live_models_snapshot"]()
assert models == frozenset()
assert known is False
assert not missing.exists(), "catalogue must never create the gateway database"
def test_broken_db_never_reports_models(tmp_path):
broken = tmp_path / "broken.db"
broken.write_bytes(b"not a sqlite database")
ns = _ns(broken)
models, known = ns["live_models_snapshot"]()
assert models == frozenset()
assert known is False
assert broken.read_bytes() == b"not a sqlite database"
def test_empty_live_set_is_known_and_authoritative(tmp_path):
db = _make_db(tmp_path / "empty.db", live=(), disabled=["qwen-max"])
ns = _ns(db)
models, known = ns["live_models_snapshot"]()
assert models == frozenset(), "disabled channels must not count as live"
assert known is True
# --- alias dedup after live/hidden filtering -----------------------------------------
def test_live_alias_survives_regardless_of_row_order(tmp_path):
"""A disabled alias must not win the dedup and drop the live model."""
db = _make_db(tmp_path / "live.db", live=["qwen-max"])
ns = _ns(db)
forward = _kept(_pricing("qwen/qwen.max", "qwen-max"), ns)
backward = _kept(_pricing("qwen-max", "qwen/qwen.max"), ns)
assert forward == ["qwen-max"]
assert backward == ["qwen-max"]
def test_hidden_row_does_not_shadow_visible_alias(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
ns = _ns(db, hide=("grok-4.6",))
kept = _kept(_pricing("grok-4.6", "grok-4.6", "x-ai/grok-4.6"), ns)
assert "grok-4.6" not in kept
assert kept == []
def test_known_empty_catalogue_drops_every_row(tmp_path):
db = _make_db(tmp_path / "empty.db", live=())
ns = _ns(db)
kept = _kept(_pricing("grok-4.6", "qwen-max"), ns)
assert kept == [], "a reachable DB with no live models must not advertise anything"
def test_unknown_state_does_not_invent_availability(tmp_path):
ns = _ns(tmp_path / "absent.db")
kept = _kept(_pricing("grok-4.6", "qwen-max"), ns)
assert kept == [], "unknown live set must fail closed, not pass every row through"
# --- cache, retry and logging --------------------------------------------------------
def test_repeated_calls_on_empty_db_read_once(tmp_path):
db = _make_db(tmp_path / "empty.db", live=())
ns = _ns(db)
clock = [100.0]
ns["_live_now"] = lambda: clock[0]
calls = _counting_read(ns)
for _ in range(25):
assert ns["get_live_models"]() == frozenset()
assert len(calls) == 1
assert ns["sink"] == []
clock[0] += ns["_LIVE_TTL"] + 1
ns["get_live_models"]()
assert len(calls) == 2, "TTL expiry must refresh exactly once"
def test_failure_is_cached_with_bounded_retry(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
ns = _ns(db)
clock = [0.0]
ns["_live_now"] = lambda: clock[0]
calls = _counting_read(ns)
assert ns["get_live_models"]() == frozenset({"grok-4.6"})
db.unlink()
clock[0] += ns["_LIVE_TTL"] + 1
for _ in range(10):
assert ns["get_live_models"]() == frozenset({"grok-4.6"}), "stale set is served on error"
assert len(calls) == 2, "a failed refresh must not re-hit the DB on every request"
assert len(ns["sink"]) == 1, "one warning per retry window, not per request"
clock[0] = ns["_LIVE_MAX_STALE"]
assert ns["live_models_snapshot"]() == (frozenset(), False)
assert len(calls) == 2, "expiry must not bypass the failure retry window"
clock[0] += ns["_LIVE_RETRY"] + 1
assert ns["live_models_snapshot"]() == (frozenset(), False)
assert len(calls) == 3, "unavailable DB cannot keep advertising the stale set"
assert len(ns["sink"]) == 2
_make_db(db, live=["new-model"])
clock[0] += ns["_LIVE_RETRY"] + 1
assert ns["get_live_models"]() == frozenset({"new-model"})
assert len(calls) == 4, "retry window must allow recovery"
def test_broken_db_stays_cached_between_requests(tmp_path):
broken = tmp_path / "broken.db"
broken.write_bytes(b"garbage")
ns = _ns(broken)
clock = [0.0]
ns["_live_now"] = lambda: clock[0]
calls = _counting_read(ns)
for _ in range(30):
models, known = ns["live_models_snapshot"]()
assert models == frozenset() and known is False
assert len(calls) == 1
assert len(ns["sink"]) == 1
def test_concurrent_refresh_runs_once(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
ns = _ns(db)
clock = [0.0]
ns["_live_now"] = lambda: clock[0]
calls = _counting_read(ns)
real = ns["_live_read"]
def slow_read():
time.sleep(0.15)
return real()
ns["_live_read"] = slow_read
results = []
barrier = threading.Barrier(8)
def worker():
barrier.wait()
results.append(ns["get_live_models"]())
threads = [threading.Thread(target=worker) for _ in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join(10)
assert not any(thread.is_alive() for thread in threads)
assert len(results) == 8
assert set(results) == {frozenset({"grok-4.6"})}
assert len(calls) == 1, "single-flight: one DB read for the whole burst"
def test_snapshot_is_immutable(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
ns = _ns(db)
models = ns["get_live_models"]()
assert isinstance(models, frozenset)
assert not hasattr(models, "add")
assert models is ns["live_models_snapshot"]()[0], "no per-request copy churn"
# --- pricing semantics unchanged -----------------------------------------------------
def test_pricing_body_preserves_billing_rules(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"])
ns = _ns(db)
raw = json.dumps({"data": [
{"model_name": "grok-4.6", "model_ratio": 4, "model_price": 0.5,
"enable_groups": ["default", "vip"]},
{"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3},
], "group_ratio": {"default": 1, "vip": 2}, "usable_group": {"default": "x", "vip": "y"}}
).encode("utf-8")
body = json.loads(ns["filter_pricing_body"](raw))
grok, kimi = body["data"]
assert grok["model_ratio"] == 2 and grok["model_price"] == 0.25
assert grok["enable_groups"] == ["default"]
assert kimi["model_ratio"] == 3, "explicit kimi tariffs must not be halved"
assert body["group_ratio"] == {"default": 1}
assert body["usable_group"] == {"default": "x"}
def test_unfiltered_body_returns_original_bytes(tmp_path):
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"]))
raw = json.dumps({"data": ["not-a-model-row"]}).encode("utf-8")
assert ns["filter_pricing_body"](raw) is raw
def test_real_rows_without_tariff_changes_return_original_bytes(tmp_path):
"""Byte identity must hold for a genuine dict payload, not only a non-dict row.
The billing pass used to flag every dict row as modified, so each pricing body
was re-serialized even when no tariff or group actually changed.
"""
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6", "kimi/kimi-k3.1-pro"]))
raw = json.dumps({"data": [
{"model_name": "grok-4.6", "enable_groups": ["default"]},
{"model_name": "kimi/kimi-k3.1-pro", "model_ratio": 3},
]}).encode("utf-8")
assert ns["filter_pricing_body"](raw) is raw
def test_halved_tariff_still_marks_the_body_changed(tmp_path):
ns = _ns(_make_db(tmp_path / "live.db", live=["grok-4.6"]))
raw = json.dumps({"data": [{"model_name": "grok-4.6", "model_ratio": 4}]}).encode("utf-8")
body = ns["filter_pricing_body"](raw)
assert body is not raw
assert json.loads(body)["data"][0]["model_ratio"] == 2
def test_empty_pricing_rows_skip_the_database_entirely(tmp_path):
db = _make_db(tmp_path / "live.db", live=["grok-4.6"])
ns = _ns(db)
calls = _counting_read(ns)
raw = json.dumps({"data": []}).encode("utf-8")
assert ns["filter_pricing_body"](raw) is raw
assert calls == []
class PricingResponsivenessTests(IsolatedAsyncioTestCase):
async def test_cold_catalogue_lookup_keeps_the_relay_event_loop_responsive(self):
loop = asyncio.get_running_loop()
entered = asyncio.Event()
release = threading.Event()
owner = threading.get_ident()
callers = []
raw = b'{"data":[{"model_name":"demo"}]}'
filtered = b'{"data":[]}'
def filter_body(body):
callers.append((body, threading.get_ident()))
loop.call_soon_threadsafe(entered.set)
if not release.wait(3):
raise AssertionError("catalogue lookup blocked the event loop")
return filtered
_, funcs = _nodes()
ns = {"asyncio": asyncio, "web": web, "SKIP": (), "LOG": logging.getLogger(__name__),
"response_headers": dict, "filter_pricing_body": filter_body}
exec(compile(ast.Module(body=[funcs["relay"]], type_ignores=[]), str(SKIN), "exec"), ns)
async def read():
return raw
request = SimpleNamespace(path="/api/pricing", method="GET")
upstream = SimpleNamespace(status=200, headers={"Content-Type": "application/json"}, read=read)
pending = asyncio.create_task(ns["relay"](request, upstream))
try:
await asyncio.wait_for(entered.wait(), 3)
self.assertFalse(pending.done())
self.assertEqual(callers[0][0], raw)
self.assertNotEqual(callers[0][1], owner)
release.set()
response = await asyncio.wait_for(pending, 3)
finally:
release.set()
if not pending.done():
await asyncio.wait_for(asyncio.gather(pending, return_exceptions=True), 3)
self.assertEqual(response.status, 200)
self.assertEqual(response.body, filtered)
self.assertEqual(response.headers["Content-Type"], "application/json")
+168
View File
@@ -37,3 +37,171 @@ def test_tg_login_refuses_cross_site_origin():
resp = asyncio.run(ns["tg_login"](req)) resp = asyncio.run(ns["tg_login"](req))
assert resp.status == 403 assert resp.status == 403
assert json.loads(resp.body)["error"] == "bad_origin" assert json.loads(resp.body)["error"] == "bad_origin"
def test_tg_login_never_holds_the_store_open_across_provisioning():
"""connect+DDL must not run on the loop, and no connection may span a network await."""
import asyncio
import logging
import os
import secrets
import sqlite3
import tempfile
from contextlib import closing
with tempfile.TemporaryDirectory() as tmp:
db = os.path.join(tmp, "tg-provision.db")
token_file = os.path.join(tmp, "admin.token")
with open(token_file, "w", encoding="utf-8") as fh:
fh.write("bearer-token\n")
state = {"opened": 0, "closed": 0, "held": [], "links": []}
class _Conn:
def __init__(self, con):
self._con = con
def __getattr__(self, name):
return getattr(self._con, name)
def close(self):
state["closed"] += 1
self._con.close()
class _Req:
headers = {"Origin": "https://example.com"}
host = "example.com"
app = {"sess": object()}
async def text(self):
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
async def _newapi_call(session, method, path, bearer, body=None):
# the store must already be closed when the request goes out
state["held"].append(state["opened"] - state["closed"])
if path == "/api/user/login":
return 200, b'{"success": false}', None
return 200, b'{"success": true, "data": {"id": 7}}', None
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
logging=logging, LOG=logging.getLogger("tg_login_store"),
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
_json_ok=lambda status, body: status == 200 and json.loads(body).get("success") is True,
_tg_link_upsert=lambda *args: state["links"].append(args))
real_conn = ns["_tg_store_conn"]
def tracked_conn():
state["opened"] += 1
return _Conn(real_conn())
ns["_tg_store_conn"] = tracked_conn
resp = asyncio.run(ns["tg_login"](_Req()))
assert resp.status == 502
assert json.loads(resp.body)["error"] == "login_failed"
# a read for the missing password plus a write once provisioning succeeded
assert state["opened"] >= 2
assert state["held"] and set(state["held"]) == {0}, state["held"]
assert state["opened"] == state["closed"]
assert state["links"] == [(123, "tg123")]
# `with sqlite3.connect(...)` commits but does not close: on Windows the open
# handle would break TemporaryDirectory cleanup.
with closing(sqlite3.connect(db)) as con:
row = con.execute("SELECT username, length(password) FROM tg_users"
" WHERE tg_id=123").fetchone()
assert row[0] == "tg123" and row[1] >= 24
def test_tg_login_provision_recovery_keeps_the_store_closed_across_awaits():
"""create->search->get->put recovery runs four round trips; no connection may span one."""
import logging
import os
import secrets
import sqlite3
import tempfile
from contextlib import closing
with tempfile.TemporaryDirectory() as tmp:
db = os.path.join(tmp, "tg-provision.db")
token_file = os.path.join(tmp, "admin.token")
with open(token_file, "w", encoding="utf-8") as fh:
fh.write("bearer-token\n")
state = {"opened": 0, "closed": 0, "held": [], "links": [], "calls": [], "put_body": None}
class _Conn:
def __init__(self, con):
self._con = con
def __getattr__(self, name):
return getattr(self._con, name)
def close(self):
state["closed"] += 1
self._con.close()
class _Req:
headers = {"Origin": "https://example.com"}
host = "example.com"
app = {"sess": object()}
async def text(self):
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
async def _newapi_call(session, method, path, bearer, body=None):
# the store must already be closed when each of the four requests goes out
state["held"].append(state["opened"] - state["closed"])
state["calls"].append((method, path))
if method == "POST" and path == "/api/user/":
return 200, b'{"success": false, "message": "username already exists"}', None
if method == "GET" and path.startswith("/api/user/search"):
return 200, b'{"success": true, "data": {"items": [{"id": 7, "username": "tg123"}]}}', None
if method == "GET" and path == "/api/user/7":
return 200, b'{"success": true, "data": {"id": 7, "username": "tg123", "display_name": "tg"}}', None
if method == "PUT" and path == "/api/user/":
state["put_body"] = body
return 200, b'{"success": true}', None
if path == "/api/user/login":
return 200, b'{"success": false}', None
return 404, b'{"success": false}', None
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
"_find_user_id", "_json_ok",
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
logging=logging, LOG=logging.getLogger("tg_login_recovery"),
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
_tg_link_upsert=lambda *args: state["links"].append(args))
real_conn = ns["_tg_store_conn"]
def tracked_conn():
state["opened"] += 1
return _Conn(real_conn())
ns["_tg_store_conn"] = tracked_conn
resp = asyncio.run(ns["tg_login"](_Req()))
assert resp.status == 502
assert json.loads(resp.body)["error"] == "login_failed"
# the whole recovery chain ran, in order, and the full user object was resent
assert state["calls"] == [("POST", "/api/user/"),
("GET", "/api/user/search?keyword=tg123"),
("GET", "/api/user/7"),
("PUT", "/api/user/"),
("POST", "/api/user/login")]
assert state["put_body"]["id"] == 7 and state["put_body"]["username"] == "tg123"
assert len(state["put_body"]["password"]) >= 24
# no connection was open while a request was in flight, and none leaked
assert state["held"] and set(state["held"]) == {0}, state["held"]
assert state["opened"] == state["closed"]
assert state["links"] == [(123, "tg123")]
# the recovered password is what the store will serve on the next login
with closing(sqlite3.connect(db)) as con:
stored = con.execute("SELECT password FROM tg_users WHERE tg_id=123").fetchone()[0]
assert stored == state["put_body"]["password"]
+7 -2
View File
@@ -78,6 +78,8 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase):
'TIMEOUT': aiohttp.ClientTimeout(total=5), 'SKIP': ('/v1/',), 'TIMEOUT': aiohttp.ClientTimeout(total=5), 'SKIP': ('/v1/',),
'_GEN_PATHS': {'/v1/chat/completions', '/v1/messages', '/v1/responses'}, '_GEN_PATHS': {'/v1/chat/completions', '/v1/messages', '/v1/responses'},
'LOG': logging.getLogger('transparent_test'), 'LOG': logging.getLogger('transparent_test'),
'public_error': public_error, 'public_json_dumps': public_json_dumps,
'secrets': secrets,
'gate_check': AsyncMock(return_value=(False, '')), '_rl_check_sync': Mock(return_value=None), 'gate_check': AsyncMock(return_value=(False, '')), '_rl_check_sync': Mock(return_value=None),
'_DEV_ROLE_INCOMPAT_PREFIXES': ("qwen", "glm", "deepseek", "kimi"), '_DEV_ROLE_INCOMPAT_PREFIXES': ("qwen", "glm", "deepseek", "kimi"),
'_key_balance_usd': Mock(return_value=None), '_key_balance_usd': Mock(return_value=None),
@@ -93,8 +95,11 @@ class PublicTransparentTests(unittest.IsolatedAsyncioTestCase):
names = {'CONTROL_SESSION_KEY', 'GENERATION_CONNECTIONS', 'CONTROL_CONNECTIONS'} 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)] 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) exec(compile(ast.Module(body=constants, type_ignores=[]), str(SKIN), 'exec'), self.ns)
# real error wire form: proxy's failure paths must exercise the offloaded
# mapping, not a stub, otherwise a reverted sync call would still pass.
extract(SKIN, {'proxy', 'response_headers', '_dev_role_incompat_model', extract(SKIN, {'proxy', 'response_headers', '_dev_role_incompat_model',
'_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions'}, self.ns) '_normalize_developer_roles', '_open_upstream_sessions', '_close_upstream_sessions',
'async_error_response', '_error_payload', '_finish_error'}, self.ns)
self.app.router.add_route('*', '/{path:.*}', self.ns['proxy']) self.app.router.add_route('*', '/{path:.*}', self.ns['proxy'])
self.client = TestClient(TestServer(self.app)) self.client = TestClient(TestServer(self.app))
await self.client.start_server() await self.client.start_server()
@@ -246,7 +251,7 @@ class PublicErrorWireTests(unittest.IsolatedAsyncioTestCase):
'public_error': public_error, 'public_json_dumps': public_json_dumps, 'public_error': public_error, 'public_json_dumps': public_json_dumps,
'LOG': logging.getLogger('error_wire_test'), 'LOG': logging.getLogger('error_wire_test'),
} }
extract(SKIN, {'error_response'}, namespace) extract(SKIN, {'error_response', '_error_payload', '_finish_error'}, namespace)
async def handler(request): async def handler(request):
return namespace['error_response']( return namespace['error_response'](