Files
iishko-public/tests/test_runtime_economy_paths.py
T
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

281 lines
14 KiB
Python

"""Economy consumers must honour the shared runtime path helpers.
Regressions cover non-default paths and conflicting aliases without importing the
whole bot runtime: econ_cap/account_admin are loaded as isolated module instances,
and the Mini App daemon helpers are AST-extracted and executed alone.
"""
import ast
from contextlib import closing
import importlib.util
import itertools
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import time
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
BOT = ROOT / "bot"
sys.path.insert(0, str(BOT))
COUNTER = itertools.count()
DEFAULT_BOT_DB = "/opt/grok-bot/bot.db"
DEFAULT_GW_DB = "/opt/grok-gateway/new-api/one-api.db"
DEFAULT_STATE = "/opt/grok-bot/econ_cap_state.json"
def _load(relative_path):
"""Load a module file by path so each case sees its own environment."""
path = BOT / relative_path
name = "econ_paths_probe_%s_%d" % (path.stem, next(COUNTER))
spec = importlib.util.spec_from_file_location(name, path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _daemon_functions(names, environ):
"""Execute only the requested functions from mk_daemon, never the module."""
source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8")
tree = ast.parse(source)
wanted = [node for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name in names]
missing = set(names) - {node.name for node in wanted}
assert not missing, "mk_daemon.py no longer defines %s" % sorted(missing)
calls = []
def econ_state_path():
calls.append(True)
return environ["IISHKO_ECON_STATE"]
namespace = {"json": json, "sqlite3": sqlite3, "econ_state_path": econ_state_path,
"calls": calls}
exec(compile(ast.Module(body=wanted, type_ignores=[]), "<mk_daemon>", "exec"), namespace)
return namespace, calls
def _module_assignments(relative_path):
tree = ast.parse((BOT / relative_path).read_text(encoding="utf-8"))
found = {}
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
found[target.id] = node.value
return found
def _calls_name(node, name):
return (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id == name)
def _mentions(node, name):
return any(isinstance(item, ast.Attribute) and item.attr == name
or isinstance(item, ast.Name) and item.id == name
for item in ast.walk(node))
class ConsumerPathTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = Path(tmp.name)
self.bot_db = str(root / "custom" / "bot.db")
self.gw_db = str(root / "custom" / "gateway.db")
self.state = str(root / "custom" / "econ_state.json")
for path in (self.bot_db, self.gw_db, self.state):
Path(path).parent.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------- econ_cap
def test_econ_cap_prefers_canonical_names(self):
env = {
"IISHKO_BOT_DB": self.bot_db,
"GROK_BOT_DB": "/legacy/bot.db",
"GATE_BOT_DB": "/legacy/gate.db",
"IISHKO_GW_DB": self.gw_db,
"GATE_NEWAPI_DB": "/legacy/gateway.db",
"IISHKO_ECON_STATE": self.state,
}
with patch.dict(os.environ, env, clear=True):
module = _load("econ_cap.py")
self.assertEqual(module.BOT_DB, self.bot_db)
self.assertEqual(module.NA_DB, self.gw_db)
self.assertEqual(module.STATE, self.state)
def test_econ_cap_keeps_legacy_aliases(self):
env = {"GROK_BOT_DB": self.bot_db, "GATE_NEWAPI_DB": self.gw_db}
with patch.dict(os.environ, env, clear=True):
module = _load("econ_cap.py")
self.assertEqual(module.BOT_DB, self.bot_db)
self.assertEqual(module.NA_DB, self.gw_db)
def test_econ_cap_ignores_empty_canonical_alias(self):
env = {"IISHKO_BOT_DB": "", "GROK_BOT_DB": self.bot_db,
"IISHKO_ECON_STATE": ""}
with patch.dict(os.environ, env, clear=True):
module = _load("econ_cap.py")
self.assertEqual(module.BOT_DB, self.bot_db)
self.assertEqual(module.STATE, DEFAULT_STATE)
def test_econ_cap_defaults_when_nothing_is_configured(self):
with patch.dict(os.environ, {}, clear=True):
module = _load("econ_cap.py")
self.assertEqual(module.BOT_DB, DEFAULT_BOT_DB)
self.assertEqual(module.NA_DB, DEFAULT_GW_DB)
self.assertEqual(module.STATE, DEFAULT_STATE)
def test_econ_cap_state_file_round_trip(self):
Path(self.state).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 7}}}),
encoding="utf-8")
with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True):
module = _load("econ_cap.py")
paused, migrated = module.load_state(archive=False)
self.assertEqual(paused, {"tg101": {"tid": 7}})
self.assertEqual(migrated, 0)
# ------------------------------------------------------------ account_admin
def test_account_admin_pause_path_uses_canonical_helper(self):
with patch.dict(os.environ, {"IISHKO_ECON_STATE": self.state}, clear=True):
module = _load("account_admin.py")
self.assertEqual(module.PAUSE_PATH, self.state)
for name in ("set_banned", "unban_account"):
default = module.__dict__[name].__kwdefaults__["pause_path"]
self.assertEqual(default, self.state, name)
def test_account_admin_pause_path_falls_back(self):
with patch.dict(os.environ, {}, clear=True):
module = _load("account_admin.py")
self.assertEqual(module.PAUSE_PATH, DEFAULT_STATE)
# --------------------------------------------------------------- mk_daemon
def test_mk_daemon_module_paths_come_from_helpers(self):
assigns = _module_assignments("webapp/mk_daemon.py")
self.assertTrue(_calls_name(assigns["BOT_DB"], "bot_db_path"),
"mk_daemon BOT_DB must use the shared bot_db_path helper")
self.assertTrue(_mentions(assigns["GW_DB"], "CFG"),
"mk_daemon GW_DB must follow the imported bot CFG")
self.assertNotIn("GROK_BOT_DB", ast.dump(assigns["BOT_DB"]),
"mk_daemon must not re-implement the bot DB alias list")
def test_mk_daemon_reads_pause_state_from_env_path(self):
Path(self.state).write_text(json.dumps({"v": 2, "paused": {}}), encoding="utf-8")
environ = {"IISHKO_ECON_STATE": self.state}
namespace, calls = _daemon_functions({"_state_path", "_read_pause_state"}, environ)
self.assertEqual(namespace["_read_pause_state"](), {"v": 2, "paused": {}})
self.assertTrue(calls, "_read_pause_state must resolve the helper by default")
def test_mk_daemon_explicit_state_override_wins(self):
other = str(Path(self.state).with_name("override.json"))
Path(other).write_text(json.dumps({"v": 2, "paused": {"tg101": {"tid": 1}}}),
encoding="utf-8")
environ = {"IISHKO_ECON_STATE": str(Path(self.state).with_name("missing.json"))}
namespace, _ = _daemon_functions({"_state_path", "_read_pause_state"}, environ)
self.assertEqual(namespace["_read_pause_state"](other),
{"v": 2, "paused": {"tg101": {"tid": 1}}})
def test_mk_daemon_daily_pause_info_lazy_read(self):
now = int(time.time())
Path(self.state).write_text(json.dumps(
{"v": 2, "paused": {"tg101": {"tid": 7, "ts": now, "prev_status": 1}}}),
encoding="utf-8")
environ = {"IISHKO_ECON_STATE": self.state}
namespace, calls = _daemon_functions({"_state_path", "_read_pause_state", "_daily_pause_info"},
environ)
with closing(sqlite3.connect(":memory:")) as con:
info = namespace["_daily_pause_info"](
con, {"status": 2, "id": 7, "name": "tg101"}, {})
self.assertTrue(info.get("daily_paused"))
self.assertGreater(info["retry_at"], now)
self.assertTrue(calls, "_daily_pause_info must read the configured state file")
def test_mk_daemon_no_hardcoded_economy_paths(self):
source = (BOT / "webapp" / "mk_daemon.py").read_text(encoding="utf-8")
self.assertNotIn("/opt/grok-bot", source)
def test_consumers_have_no_hardcoded_economy_paths(self):
for relative in ("econ_cap.py", "account_admin.py"):
source = (BOT / relative).read_text(encoding="utf-8")
self.assertNotIn(DEFAULT_STATE, source, relative)
self.assertNotIn(DEFAULT_BOT_DB, source, relative)
self.assertNotIn(DEFAULT_GW_DB, source, relative)
class EntryAndNotificationPathsTests(unittest.TestCase):
def test_entry_admin_initializes_only_the_selected_alias_database(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
for alias in ("IISHKO_BOT_DB", "GROK_BOT_DB", "GATE_BOT_DB"):
with self.subTest(alias=alias):
db = root / (alias + ".db")
with patch.dict(os.environ, {alias: str(db)}, clear=True):
module = _load("entry_admin.py")
self.assertEqual(module.BOT_DB, str(db))
module.init_db()
with closing(sqlite3.connect(db)) as con:
self.assertIsNotNone(con.execute(
"SELECT name FROM sqlite_master WHERE name='wa_entry_tags'").fetchone())
def test_entry_admin_binding_follows_the_effective_application_database(self):
for relative, module_name in (("grok_bot.py", "_entry_admin"),
("webapp/server.py", "entry_admin")):
with self.subTest(source=relative):
tree = ast.parse((BOT / relative).read_text(encoding="utf-8"))
bindings = [node for node in tree.body if isinstance(node, ast.Assign)
and any(isinstance(target, ast.Attribute)
and isinstance(target.value, ast.Name)
and target.value.id == module_name and target.attr == "BOT_DB"
for target in node.targets)]
self.assertEqual(len(bindings), 1)
self.assertEqual(ast.dump(bindings[0].value), ast.dump(ast.Name(id="BOT_DB", ctx=ast.Load())))
bot_db = _module_assignments(relative)["BOT_DB"]
self.assertEqual(ast.dump(bot_db), ast.dump(ast.parse('CFG["bot_db"]', mode="eval").body))
self.assertTrue(any(isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id == "effective_bot_config" for node in ast.walk(tree)))
def test_notification_cli_honours_config_env_and_explicit_paths_without_writing(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
config_db, env_db, explicit_db = (root / name for name in ("config.db", "env.db", "explicit.db"))
for db in (config_db, env_db, explicit_db):
with closing(sqlite3.connect(db)) as con:
con.execute("CREATE TABLE users(tg_id INTEGER,created INTEGER,privacy_ok INTEGER,banned INTEGER,lang TEXT)")
con.commit()
config = root / "config.json"
config.write_text(json.dumps({"bot_db": str(config_db), "key_wait_hours": 2}), encoding="utf-8-sig")
before = {db: db.read_bytes() for db in (config_db, env_db, explicit_db)}
base_env = {key: value for key, value in os.environ.items()
if not key.startswith(("IISHKO_", "GROK_", "GATE_"))}
scenarios = [
({"GATE_BOT_CONFIG": str(config)}, []),
({"GROK_BOT_CONFIG": str(config), "IISHKO_BOT_DB": str(env_db)}, []),
({"GROK_BOT_CFG": str(config), "GATE_BOT_DB": str(env_db)}, []),
({"GROK_BOT_CFG": str(config), "IISHKO_BOT_DB": str(root / "absent.db")},
["--bot-db", str(explicit_db)]),
]
for variables, args in scenarios:
with self.subTest(variables=sorted(variables), explicit=bool(args)):
configured_db = root / "config-should-not-be-opened.db" if any(
key.endswith("BOT_DB") for key in variables) else config_db
config.write_text(json.dumps({"bot_db": str(configured_db), "key_wait_hours": 2}),
encoding="utf-8-sig")
result = subprocess.run([sys.executable, str(BOT / "key_notifications.py"), "dry-run", *args],
cwd=root, env={**base_env, **variables}, capture_output=True,
text=True, encoding="utf-8", timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout)["wait_seconds"], 7200)
self.assertFalse((root / "absent.db").exists())
self.assertFalse((root / "config-should-not-be-opened.db").exists())
self.assertFalse((root / "key_notifications.sqlite3").exists())
self.assertEqual({db: db.read_bytes() for db in before}, before)
if __name__ == "__main__":
unittest.main()