IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
"""Execute the real proxy AST with isolated auth and upstream boundaries; no network/DB."""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import sys
|
||||
import time
|
||||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
import pytest
|
||||
from yarl import URL
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from request_effort import InvalidEffort, read_effort
|
||||
|
||||
SKINS = [ROOT / "gateway" / "grok-web-skin.py"]
|
||||
if os.environ.get("IISHKO_CANDIDATE_SKIN"):
|
||||
SKINS.append(Path(os.environ["IISHKO_CANDIDATE_SKIN"]))
|
||||
|
||||
|
||||
def exercise(source, endpoint, payload, blocked=False):
|
||||
tree = ast.parse(source.read_text(encoding="utf-8"))
|
||||
names = {"proxy", "_dev_role_incompat_model", "_normalize_developer_roles"}
|
||||
nodes: list[ast.stmt] = [node for node in tree.body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
|
||||
assert {node.name for node in nodes if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))} == names
|
||||
sent = []
|
||||
gates = []
|
||||
raw = (" " + json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode()
|
||||
|
||||
class Session:
|
||||
closed = False
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
sent.append((method, str(url), kwargs["data"]))
|
||||
return self
|
||||
|
||||
async def __aenter__(self):
|
||||
return SimpleNamespace(status=200)
|
||||
|
||||
async def __aexit__(self, *args):
|
||||
return False
|
||||
|
||||
async def gate(key):
|
||||
gates.append(key)
|
||||
return blocked, "Access denied"
|
||||
|
||||
async def relay(*args, **kwargs):
|
||||
return web.Response(body=b'{"ok":true}', content_type="application/json")
|
||||
|
||||
async def relay_request(req, session, url, *, body, **kwargs):
|
||||
async with session.request(req.method, url, data=body) as upstream:
|
||||
return await relay(req, upstream)
|
||||
|
||||
async def read():
|
||||
return raw
|
||||
|
||||
namespace = {
|
||||
"asyncio": asyncio, "aiohttp": aiohttp, "json": json, "time": time,
|
||||
"web": web, "URL": URL, "LOG": logging.getLogger(__name__),
|
||||
"InvalidEffort": InvalidEffort, "read_effort": read_effort,
|
||||
"normalize_auth_headers": dict, "response_headers": dict,
|
||||
"GateUnavailable": type("GateUnavailable", (Exception,), {}),
|
||||
"gate_check": gate, "_rl_check_sync": lambda *args: None,
|
||||
"_DEV_ROLE_INCOMPAT_PREFIXES": ("qwen", "glm", "deepseek", "kimi"),
|
||||
"SKIP": (), "_GEN_PATHS": ("/v1/chat/completions", "/v1/responses"),
|
||||
"SESSION_KEY": "generation", "CONTROL_SESSION_KEY": "control",
|
||||
"PROVIDER_KEY": "provider", "UPSTREAM": "http://isolated.invalid",
|
||||
"_key_balance_usd": lambda *args: None,
|
||||
"relay_api": relay, "relay_api_request": relay_request,
|
||||
}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])),
|
||||
str(source), "exec"), namespace)
|
||||
req = SimpleNamespace(path=endpoint, raw_path=endpoint, method="POST", cookies={},
|
||||
headers={"Authorization": "Bearer isolated-test"}, read=read,
|
||||
app={"generation": Session()})
|
||||
response = asyncio.run(namespace["proxy"](req))
|
||||
assert gates == ["isolated-test"], "account policy must still run before dispatch"
|
||||
return response, sent, raw
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/chat/completions", "/v1/responses"])
|
||||
@pytest.mark.parametrize("effort", [{"reasoning_effort": "low"},
|
||||
{"reasoning": {"effort": "high"}},
|
||||
{"reasoning_effort": "high", "reasoning": {"effort": "high"}}])
|
||||
def test_effort_reaches_upstream_without_reserializing(skin, endpoint, effort):
|
||||
payload = {"model": "deepseek-v4-pro", "messages": [{"role": "user", "content": "Привет"}],
|
||||
"tools": [], "stream": True, **effort}
|
||||
response, sent, raw = exercise(skin, endpoint, payload)
|
||||
assert response.status == 200 and response.body == b'{"ok":true}'
|
||||
assert len(sent) == 1
|
||||
assert sent[0][2] == raw
|
||||
assert json.loads(sent[0][2]) == payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
@pytest.mark.parametrize("endpoint", ["/v1/chat/completions", "/v1/responses"])
|
||||
@pytest.mark.parametrize("effort", [{"effort": "high"}, {"reasoning_effort": 1},
|
||||
{"reasoning_effort": " "},
|
||||
{"reasoning_effort": "low", "reasoning": {"effort": "high"}}])
|
||||
def test_invalid_effort_never_dispatches(skin, endpoint, effort):
|
||||
response, sent, _ = exercise(skin, endpoint, {"model": "deepseek-v4-pro", **effort})
|
||||
assert response.status == 400
|
||||
assert json.loads(response.body)["error"]["code"] == "invalid_effort"
|
||||
assert not sent
|
||||
|
||||
|
||||
@pytest.mark.parametrize("skin", SKINS, ids=lambda p: p.name)
|
||||
def test_effort_does_not_bypass_account_policy(skin):
|
||||
response, sent, _ = exercise(skin, "/v1/chat/completions",
|
||||
{"model": "deepseek-v4-pro", "reasoning_effort": "high"}, blocked=True)
|
||||
assert response.status == 403
|
||||
assert json.loads(response.body)["error"]["code"] == "access_blocked"
|
||||
assert not sent
|
||||
Reference in New Issue
Block a user