Files
iishko-public/tests/test_runtime_startup.py
Vlad Gothbreach af292ff15d
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
Harden entry safety, unify runtime config, bound document unpacking
Shared-IP safety: entry autoban and entry notifications default off, and a
shared IP is treated as review evidence only. ban_user/ban_cluster refuse
reason=entry_ip_collision (also with the legacy flag set to 1), so token status
and quota are never touched; explicit admin moderation still works.

Reproducible startup: new bot/runtime_config.py and scripts/run.py load the
repository .env (or --env-file) without shell interpolation, normalize
config/DB/upstream aliases, and make the bot, Mini App, gateway, econ cap,
account admin, mk_daemon, entry admin and key notifications resolve the same
paths. "run.py <target> --check" is an offline preflight that starts nothing
and reports placeholders, missing upstream DB and invalid data directories.

Resource limits: aggregate Office decompression, a 400 read-entry cap and a
per-row XLSX cell budget stop early; truncated or corrupt archives are
reported instead of raising.

Deploy and docs: only source-backed systemd units remain, and
deploy/runtime.env.example documents the environment contract including the
0600 session-secret file rules. Removed the destructive
"cp bot/iishko_bot.py bot/grok_bot.py" instruction, the unused generated site/
snapshot and the unsupported iishko-ts staging unit; corrected .env.example,
README, ARCHITECTURE, SECURITY, docs/native-gateway.md and iishko-ts/README.md.

Tests: entry safety, runtime bootstrap, economy paths, file intake, deploy
contract, abilities_guard CLI, and a startup smoke that launches all three
components through scripts/run.py with non-loopback network blocked. Every
config reader, selfcheck included, accepts a UTF-8 BOM.

Verified on this tree: pytest 716 passed + 322 subtests, node --test 73/73,
go test and go vet clean, selfcheck --source-only ok, gitleaks worktree and
history 0 findings. No production or live-split changes are included.
2026-10-31 00:39:35 +03:00

470 lines
17 KiB
Python

"""Startup smoke tests: every entrypoint is launched through ``scripts/run.py``.
Each test starts a real child interpreter with a scratch ``--env-file``; the
child bootstrap (a temporary ``sitecustomize``) forbids non-loopback network
access, and the bot child replaces the Telegram transport at the boundary with
one that only answers the calls a healthy startup needs. The bot test proves
that the real dispatcher reaches polling and that background workers were
registered and cancelled; the web app and gateway tests prove their listener
answers a request that touches neither SQLite business tables nor upstreams.
Nothing here starts production services: all writable paths (databases, icons,
key files, secret file, economy state) come from the generated env file, and
all listening ports are loopback ports reserved and released by the test.
"""
from __future__ import annotations
import hashlib
import json
import os
import socket
import sqlite3
import subprocess
import sys
import textwrap
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LAUNCHER = ROOT / "scripts" / "run.py"
APP_ENV_PREFIXES = ("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "TELEGRAM_", "TG_")
STRIPPED_ENV = frozenset(
{"PYTHONHOME", "PYTHONSTARTUP", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"})
STARTUP_TIMEOUT = 120.0
HTTP_TIMEOUT = 2.0
HTTP_POLL_INTERVAL = 0.2
# Defaults in bot/grok_bot.py, bot/runtime_config.py and gateway/grok-web-skin.py.
# A test that writes any of these has leaked a production path.
HARDCODED_STARTUP_PATHS = (
Path("C:/opt/grok-bot/bot.db"),
Path("C:/opt/grok-bot/icons.json"),
Path("C:/opt/grok-bot/econ_cap_state.json"),
Path("C:/opt/grok-gateway/new-api/one-api.db"),
Path("C:/opt/grok-web-skin-tg.db"),
Path("C:/root/.secrets/newapi_admin_token"),
Path("C:/root/iishko_audit.jsonl"),
)
CHILD_BOOTSTRAP = r'''
"""Temporary bootstrap injected via PYTHONPATH into every smoke child."""
import atexit
import inspect
import ipaddress
import json
import os
import socket
import sqlite3
import sys
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain", "ip6-localhost"})
_STATE = {"methods": [], "polling": 0, "routers": 0, "workers_at_polling": 0, "tasks": []}
def _blocked(host):
if host is None or host == "" or host is False:
return False # bind on all interfaces / local resolution without a host
if isinstance(host, bytes):
host = host.decode("ascii", "replace")
host = str(host)
if host in _LOOPBACK_NAMES:
return False
try:
return not ipaddress.ip_address(host).is_loopback
except ValueError:
return True # a real DNS name; startup must not need it
def _guard(address):
if isinstance(address, str):
return # AF_UNIX path
if not isinstance(address, tuple) or not address:
raise PermissionError("SMOKE_NETGUARD: unsupported socket address %r" % (address,))
if _blocked(address[0]):
raise PermissionError("SMOKE_NETGUARD: blocked network address %r" % (address,))
def _install_netguard():
real_connect = socket.socket.connect
real_connect_ex = socket.socket.connect_ex
real_sendto = socket.socket.sendto
real_create_connection = socket.create_connection
real_getaddrinfo = socket.getaddrinfo
real_gethostbyname = socket.gethostbyname
real_gethostbyname_ex = socket.gethostbyname_ex
real_getnameinfo = socket.getnameinfo
def connect(self, address):
_guard(address)
return real_connect(self, address)
def connect_ex(self, address):
_guard(address)
return real_connect_ex(self, address)
def sendto(self, data, *args):
if args:
_guard(args[-1])
return real_sendto(self, data, *args)
def create_connection(address, *args, **kwargs):
_guard(address)
return real_create_connection(address, *args, **kwargs)
def getaddrinfo(host, port, *args, **kwargs):
if _blocked(host):
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
return real_getaddrinfo(host, port, *args, **kwargs)
def gethostbyname(host):
if _blocked(host):
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
return real_gethostbyname(host)
def gethostbyname_ex(host):
if _blocked(host):
raise PermissionError("SMOKE_NETGUARD: blocked DNS lookup %r" % (host,))
return real_gethostbyname_ex(host)
def getnameinfo(sockaddr, flags):
if isinstance(sockaddr, tuple) and sockaddr:
_guard(sockaddr)
return real_getnameinfo(sockaddr, flags)
socket.socket.connect = connect
socket.socket.connect_ex = connect_ex
socket.socket.sendto = sendto
socket.create_connection = create_connection
socket.getaddrinfo = getaddrinfo
socket.gethostbyname = gethostbyname
socket.gethostbyname_ex = gethostbyname_ex
socket.getnameinfo = getnameinfo
def _install_bot_fake():
from aiogram import Dispatcher
from aiogram.client.session.aiohttp import AiohttpSession
async def make_request(self, bot, method, timeout=None, **kwargs):
from aiogram.types import ChatMemberMember, User
name = type(method).__name__
_STATE["methods"].append(name)
if name == "GetMe":
return User(id=424242424, is_bot=True, first_name="Smoke", username="smoke_bot")
if name in ("DeleteWebhook", "SetMyCommands"):
return True
if name == "GetChatMember":
return ChatMemberMember(user=User(id=424242425, is_bot=False, first_name="Smoke"))
raise AssertionError("SMOKE_BOT_FAKE: unexpected Telegram method " + name)
async def start_polling(self, *args, **kwargs):
_STATE["polling"] += 1
_STATE["routers"] = len(getattr(self, "sub_routers", ()))
caller = inspect.currentframe().f_back
workers = (caller.f_globals.get("_BG_WORKERS") or {}) if caller is not None else {}
_STATE["workers_at_polling"] = len(workers)
_STATE["tasks"] = [task for task in workers.values() if task is not None]
raise SystemExit(0)
AiohttpSession.make_request = make_request
Dispatcher.start_polling = start_polling
def _dump():
path = os.environ.get("SMOKE_RESULT_FILE")
if not path:
return
payload = {
"polling": _STATE["polling"],
"routers": _STATE["routers"],
"workers_at_polling": _STATE["workers_at_polling"],
"tasks_pending": sum(1 for task in _STATE["tasks"] if not task.done()),
"methods": list(_STATE["methods"]),
}
database = os.environ.get("IISHKO_BOT_DB")
if database and os.path.isfile(database):
try:
connection = sqlite3.connect(database)
try:
payload["tables"] = connection.execute(
"SELECT count(*) FROM sqlite_master WHERE type='table'").fetchone()[0]
finally:
connection.close()
except sqlite3.Error as error:
payload["tables_error"] = type(error).__name__
with open(path, "w", encoding="utf-8") as sink:
json.dump(payload, sink)
if os.environ.get("SMOKE_NETGUARD") == "1":
_install_netguard()
if os.environ.get("SMOKE_FAKE_BOT") == "1":
_install_bot_fake()
atexit.register(_dump)
'''
def _fake_secret(seed: str) -> str:
return hashlib.sha256(("iishko-smoke:" + seed).encode("utf-8")).hexdigest()
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def _free_ports(count: int) -> list[int]:
ports: list[int] = []
while len(ports) < count:
port = _free_port()
if port not in ports:
ports.append(port)
return ports
def _write_json(path: Path, payload: object) -> None:
# utf-8-sig mirrors what operators hand-write on Windows; every entrypoint must accept it.
path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8-sig")
def _create_sqlite(path: Path, statements: tuple[str, ...]) -> None:
connection = sqlite3.connect(path)
try:
for statement in statements:
connection.execute(statement)
connection.commit()
finally:
connection.close()
def _runtime(tmp_path: Path, target: str) -> dict:
"""Write every writable path into an env file; return the launch description."""
workdir = tmp_path / "runtime"
workdir.mkdir()
bootstrap = tmp_path / "bootstrap"
bootstrap.mkdir()
(bootstrap / "sitecustomize.py").write_text(textwrap.dedent(CHILD_BOOTSTRAP), encoding="utf-8")
paths = {
"config": workdir / "config.json",
"icons": workdir / "icons.json",
"bot_db": workdir / "bot.db",
"newapi_db": workdir / "newapi.db",
"skin_db": workdir / "skin.db",
"econ_state": workdir / "econ_cap_state.json",
"uptime_db": workdir / "uptime.db",
"support_db": workdir / "support.db",
"bot_source": workdir / "fake_bot_source.py",
"tg_secret": workdir / "tg_sid_secret",
"afkeys": workdir / "afkeys.json",
"kie_pool": workdir / "kie_pool.json",
"kie_dead": workdir / "kie_dead.json",
"pikeys": workdir / "pikeys.json",
"stdout": workdir / "child.stdout",
"stderr": workdir / "child.stderr",
"result": workdir / "result.json",
"env": workdir / "runtime.env",
}
ports = dict(zip(("webapp", "gateway", "upstream"), _free_ports(3)))
_write_json(paths["config"], {
"bot_token": "424242424:" + _fake_secret("bot-token"),
"main_key": "sk-" + _fake_secret("main-key"),
"channel_username": "@smoke_channel",
"newapi_pass": "np-" + _fake_secret("newapi-pass")[:32],
"newapi_db": paths["newapi_db"].as_posix(),
"newapi_url": "http://127.0.0.1:%d" % ports["upstream"],
})
_write_json(paths["icons"], {})
paths["bot_source"].write_text(
"TIER_MODELS = {1: ['smoke-model'], 2: ['smoke-model'], 3: ['smoke-model']}\n"
"MODEL_DESCS = {'smoke-model': 'smoke'}\n"
"TIER_TITLES = {1: 'Smoke', 2: 'Smoke', 3: 'Smoke'}\n"
"MEDIA_MODELS = {}\n",
encoding="utf-8",
)
paths["tg_secret"].write_bytes(bytes.fromhex(_fake_secret("tg-sid")))
_create_sqlite(paths["newapi_db"], (
"CREATE TABLE tokens (id INTEGER PRIMARY KEY, name TEXT, status INTEGER)",
))
if target == "gateway":
# gate_boot_selfcheck() counts rows over these columns.
_create_sqlite(paths["bot_db"], (
"CREATE TABLE users (tg_id INTEGER PRIMARY KEY, api_blocked INTEGER, "
"api_block_reason TEXT, banned INTEGER)",
))
values = {
"GROK_BOT_CFG": paths["config"].as_posix(),
"IISHKO_BOT_DB": paths["bot_db"].as_posix(),
"IISHKO_GW_DB": paths["newapi_db"].as_posix(),
"IISHKO_SKIN_DB": paths["skin_db"].as_posix(),
"IISHKO_ECON_STATE": paths["econ_state"].as_posix(),
"GROK_UPTIME_DB": paths["uptime_db"].as_posix(),
"GROK_SUPPORT_DB": paths["support_db"].as_posix(),
"IISHKO_BOT_SOURCE": paths["bot_source"].as_posix(),
"TG_SID_SECRET_FILE": paths["tg_secret"].as_posix(),
"GROK_ICONS": paths["icons"].as_posix(),
"AFKEYS": paths["afkeys"].as_posix(),
"KIE_POOL": paths["kie_pool"].as_posix(),
"KIE_DEAD": paths["kie_dead"].as_posix(),
"PIKEYS": paths["pikeys"].as_posix(),
"GW_NEWAPI_DB": paths["newapi_db"].as_posix(),
"IISHKO_UPSTREAM": "http://127.0.0.1:%d" % ports["upstream"],
"IISHKO_WEBAPP_HOST": "127.0.0.1",
"IISHKO_WEBAPP_PORT": str(ports["webapp"]),
"IISHKO_GATEWAY_HOST": "127.0.0.1",
"IISHKO_GATEWAY_PORT": str(ports["gateway"]),
"GROK_BOT_ALLOW_LOCAL": "1",
"IISHKO_NOTIFICATIONS_ENABLED": "0",
"IISHKO_SUPPORT_DELIVERY_ENABLED": "0",
"IISHKO_ENTRY_DELIVERY_ENABLED": "0",
}
paths["env"].write_text(
"".join("%s=%s\n" % item for item in values.items()), encoding="utf-8")
return {"target": target, "tmp": tmp_path, "bootstrap": bootstrap,
"paths": paths, "ports": ports}
def _child_env(runtime: dict, fake_bot: bool) -> dict[str, str]:
env = {
key: value for key, value in os.environ.items()
if not key.upper().startswith(APP_ENV_PREFIXES) and key.upper() not in STRIPPED_ENV
}
env.update({
"TMP": str(runtime["tmp"]),
"TEMP": str(runtime["tmp"]),
"PYTHONPATH": str(runtime["bootstrap"]),
"PYTHONDONTWRITEBYTECODE": "1",
"PYTHONIOENCODING": "utf-8",
"SMOKE_NETGUARD": "1",
"SMOKE_FAKE_BOT": "1" if fake_bot else "0",
"SMOKE_RESULT_FILE": str(runtime["paths"]["result"]),
})
return env
def _spawn(runtime: dict, fake_bot: bool = False) -> subprocess.Popen:
paths = runtime["paths"]
with open(paths["stdout"], "wb") as out, open(paths["stderr"], "wb") as err:
process = subprocess.Popen(
[sys.executable, str(LAUNCHER), runtime["target"],
"--env-file", str(paths["env"])],
cwd=str(ROOT), env=_child_env(runtime, fake_bot),
stdin=subprocess.DEVNULL, stdout=out, stderr=err,
)
return process
def _tail(path: Path) -> str:
try:
return path.read_text(encoding="utf-8", errors="replace")[-4000:]
except OSError:
return "<no output>"
def _failure(summary: str, process: subprocess.Popen, runtime: dict) -> str:
paths = runtime["paths"]
return "%s\nreturncode=%r\nstdout:\n%s\nstderr:\n%s" % (
summary, process.returncode, _tail(paths["stdout"]), _tail(paths["stderr"]))
def _terminate(process: subprocess.Popen) -> None:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=20)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=20)
def _wait_http(process: subprocess.Popen, url: str, runtime: dict) -> tuple[int, str]:
parts = urllib.parse.urlsplit(url)
if parts.scheme != "http" or parts.hostname not in ("127.0.0.1", "::1"):
raise AssertionError("smoke requests must stay on loopback: " + url)
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
deadline = time.monotonic() + STARTUP_TIMEOUT
while time.monotonic() < deadline:
if process.poll() is not None:
raise AssertionError(_failure("process exited before serving " + url, process, runtime))
try:
with opener.open(url, timeout=HTTP_TIMEOUT) as response:
return response.status, response.read().decode("utf-8", "replace")
except (urllib.error.URLError, OSError):
time.sleep(HTTP_POLL_INTERVAL)
raise AssertionError(_failure("no HTTP response from " + url, process, runtime))
def _hardcoded_paths_seen() -> set[str]:
return {str(path) for path in HARDCODED_STARTUP_PATHS if path.exists()}
def _assert_no_new_hardcoded_paths(before: set[str], runtime: dict) -> None:
created = _hardcoded_paths_seen() - before
assert not created, "startup wrote hardcoded operator paths: %s" % sorted(created)
def test_bot_reaches_polling_through_launcher(tmp_path):
runtime = _runtime(tmp_path, "bot")
before = _hardcoded_paths_seen()
process = _spawn(runtime, fake_bot=True)
try:
returncode = process.wait(timeout=STARTUP_TIMEOUT)
finally:
_terminate(process)
assert returncode == 0, _failure("bot child failed", process, runtime)
result = json.loads((runtime["paths"]["result"]).read_text(encoding="utf-8"))
assert result["polling"] == 1, result
assert result["routers"] >= 1, result
assert result["workers_at_polling"] >= 1, result
assert result["tasks_pending"] == 0, result
assert result.get("tables", 0) >= 5, result
methods = result["methods"]
assert "GetMe" in methods, methods
assert "GetUpdates" not in methods, methods
assert set(methods) <= {"GetMe", "DeleteWebhook", "SetMyCommands", "GetChatMember"}, methods
# The database exists only at the path handed over by --env-file.
assert runtime["paths"]["bot_db"].is_file()
_assert_no_new_hardcoded_paths(before, runtime)
def test_miniapp_serves_healthz_through_launcher(tmp_path):
runtime = _runtime(tmp_path, "miniapp")
before = _hardcoded_paths_seen()
process = _spawn(runtime)
try:
url = "http://127.0.0.1:%d/healthz" % runtime["ports"]["webapp"]
status, body = _wait_http(process, url, runtime)
assert status == 200 and "ok" in body, (status, body)
assert process.poll() is None, _failure("webapp exited after serving", process, runtime)
finally:
_terminate(process)
_assert_no_new_hardcoded_paths(before, runtime)
def test_gateway_serves_robots_through_launcher(tmp_path):
runtime = _runtime(tmp_path, "gateway")
before = _hardcoded_paths_seen()
process = _spawn(runtime)
try:
url = "http://127.0.0.1:%d/robots.txt" % runtime["ports"]["gateway"]
status, body = _wait_http(process, url, runtime)
assert status == 200, (status, body)
assert "User-agent: *" in body and "Sitemap:" in body, body
assert process.poll() is None, _failure("gateway exited after serving", process, runtime)
finally:
_terminate(process)
_assert_no_new_hardcoded_paths(before, runtime)