import asyncio from contextlib import closing import hmac import ipaddress import json import logging from pathlib import Path import re import sqlite3 import time from aiohttp import web log = logging.getLogger('gateway_policy') OWNER = re.compile(r'(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z') GENERATION_PATHS = frozenset(('/v1/chat/completions', '/v1/completions', '/v1/messages', '/v1/responses', '/v1/images/generations', '/v1/images/edits', '/v1/images/variations', '/v1/embeddings', '/v1/audio/speech', '/v1/audio/transcriptions', '/v1/audio/translations')) def _connect(path): con = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True, timeout=10) con.execute('PRAGMA query_only=ON') return con def inspect_token(newapi_db, bot_db, raw_key, model, now=None, model_access=None): """Return an explicit denial or None. All reads are WAL-consistent and query-only.""" now = int(time.time()) if now is None else now with closing(_connect(newapi_db)) as con: row = con.execute( 'SELECT t.id,t.name,t.status,t.expired_time,t.remain_quota,t.unlimited_quota,' 't.model_limits_enabled,t.model_limits,u.status FROM tokens t ' 'JOIN users u ON u.id=t.user_id AND u.deleted_at IS NULL ' 'WHERE t.key=? AND t.deleted_at IS NULL LIMIT 1', (raw_key,)).fetchone() if not row: return 401, 'invalid_api_key', 'API-ключ не найден. Актуальные ключи доступны в Mini App.' tid, name, status, expired, remain, unlimited, limited, models, user_status = row if user_status != 1: return 403, 'account_disabled', 'Аккаунт API заблокирован. Обратитесь в поддержку.' if status == 4 and not unlimited and (remain or 0) <= 0: return 402, 'insufficient_quota', 'На ключе нет API-кредита. Переведите баланс в Mini App.' if status != 1: if status == 2 and con.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'").fetchone(): paused = con.execute('SELECT 1 FROM wa_daily_cap_pauses WHERE tid=? AND name=?', (tid, name)).fetchone() if paused: return 429, 'daily_budget_exhausted', ('Дневной бюджет API исчерпан. Баланс сохранён; ' 'доступ восстановится после 00:00 МСК.') return 403, 'api_key_disabled', 'API-ключ приостановлен. Проверьте его состояние в Mini App.' if expired and expired > 0 and expired <= now: return 401, 'api_key_expired', 'Срок действия API-ключа истёк.' if not unlimited and (remain or 0) <= 0: return 402, 'insufficient_quota', 'Недостаточно API-кредита. Проверьте баланс в Mini App.' token_models = {m.strip() for m in (models or '').split(',') if m.strip()} identity = OWNER.fullmatch(name or '') allowed = not limited or model in token_models if model and identity and model_access is not None: allowed = model_access(int(identity[1]), model, token_models, allowed) if model and not allowed: return 403, 'model_access_denied', ('У ключа нет доступа к выбранной модели. Проверьте точное ' 'имя в /v1/models, свой ранг и срок действия доступа в Mini App.') match = OWNER.fullmatch(name or '') if match: with closing(_connect(bot_db)) as con: user = con.execute('SELECT banned,api_blocked,api_block_reason FROM users WHERE tg_id=?', (int(match[1]),)).fetchone() if not user: return 403, 'account_not_found', 'Аккаунт ключа не найден. Откройте бота и обратитесь в поддержку.' if user[0]: return 403, 'account_banned', 'Аккаунт заблокирован. Апелляция: @reformboss' if user[1]: return 403, 'access_blocked', user[2] or 'Доступ приостановлен. Откройте бота и выполните условия доступа.' return None def denial_response(denial, request_id=None): status, code, message = denial gateway_status = 'degraded' if status >= 500 else 'operational' error = {'message': message, 'type': 'gateway_error', 'code': code, 'retryable': status in (429, 503, 504), 'gateway_status': gateway_status} headers = {'Cache-Control': 'no-store', 'X-Gateway-Status': gateway_status} if status in (503, 504): headers['Retry-After'] = '2' if request_id: error['request_id'] = request_id headers['X-Request-ID'] = request_id return web.json_response({'error': error}, status=status, headers=headers) def create_handler(newapi_db, bot_db, secret, consume=None, check_access=None, allowed_models=None, quota_snapshot=None, model_access=None): async def authorize(req): request_id = req.headers.get('X-Request-ID', '') if not re.fullmatch(r'[0-9a-f]{32}', request_id): request_id = None async def result(response, raw_key): if quota_snapshot is not None: try: from gateway_usage import quota_headers snapshot = await asyncio.to_thread(quota_snapshot, raw_key) response.headers.update(quota_headers(snapshot)) if response.status == 429 and snapshot and snapshot.get('reset_at'): response.headers['Retry-After'] = str(max(1, snapshot['reset_at'] - int(time.time()))) except (sqlite3.Error, ValueError, TypeError, OSError): log.warning('daily_metadata_unavailable') response.headers['X-Iishko-Daily-Status'] = 'unavailable' return response try: local = ipaddress.ip_address(req.remote or '').is_loopback except ValueError: local = False supplied = req.headers.get('X-Gateway-Policy-Token', '') if not local or not secret or not hmac.compare_digest(supplied.encode(), secret.encode()): return denial_response((403, 'policy_auth_failed', 'Internal authorization required.'), request_id) if req.content_length and req.content_length > 16 * 1024: return denial_response((413, 'invalid_policy_request', 'Policy payload too large.'), request_id) try: raw = bytearray() async for chunk in req.content.iter_chunked(4096): raw.extend(chunk) if len(raw) > 16 * 1024: return denial_response((413, 'invalid_policy_request', 'Policy payload too large.'), request_id) payload = json.loads(raw) if not isinstance(payload, dict): raise ValueError('not an object') path, method, model = (payload.get(k, '') for k in ('path', 'method', 'model')) if not all(isinstance(v, str) for v in (path, method, model)): raise ValueError('invalid fields') if not path.startswith('/v1/') or method not in ('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS') or len(model) > 4096: raise ValueError('invalid policy scope') auth = req.headers.get('Authorization', '').split() if len(auth) != 2 or auth[0].lower() != 'bearer': return denial_response((401, 'missing_api_key', 'An API key is required.'), request_id) raw_key = auth[1].removeprefix('sk-') verdict = await asyncio.to_thread(inspect_token, newapi_db, bot_db, raw_key, model, model_access=model_access) if verdict: response = denial_response(verdict, request_id) return await result(response, raw_key) if verdict[1] == 'daily_budget_exhausted' else response if allowed_models is not None and model and model not in allowed_models: return denial_response((404, 'model_not_found', 'Модель не входит в проверенный каталог. Список: /v1/models.'), request_id) if check_access is not None: blocked, reason = await check_access(raw_key) if blocked: return denial_response((403, 'access_blocked', reason), request_id) if consume is not None and method == 'POST' and path in GENERATION_PATHS: verdict = await asyncio.to_thread(consume, raw_key, model) if verdict: code = 'daily_limit' if verdict[0] == 429 else 'policy_unavailable' return await result(denial_response((verdict[0], code, verdict[1]), request_id), raw_key) return await result(web.Response(status=204, headers={'Cache-Control': 'no-store'}), raw_key) except (ValueError, TypeError): return denial_response((400, 'invalid_policy_request', 'Invalid policy payload.'), request_id) except Exception: log.exception('gateway_policy_unavailable') return denial_response((503, 'policy_unavailable', 'Проверка доступа временно недоступна. Запрос провайдеру не отправлен.'), request_id) return authorize