Files
iishko-public/tests/test_entry_safety.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

111 lines
6.3 KiB
Python

"""Real SQLite regressions: shared networks cannot alter accounts or balances."""
import ast
from contextlib import closing
import json
import logging
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "bot"))
import entry_autoban
from entry_telemetry import EntryTelemetry, delivery_enabled, notification_text
from runtime_config import skin_db_path
class EntrySafetyTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
root = Path(tmp.name)
self.bot, self.gateway, self.skin = (str(root / name) for name in ("bot.db", "gateway.db", "custom-skin.db"))
with closing(sqlite3.connect(self.bot)) as con, con:
con.executescript("CREATE TABLE users(tg_id INTEGER PRIMARY KEY, username TEXT, banned INTEGER DEFAULT 0,"
"privacy_ok INTEGER DEFAULT 1, admin INTEGER DEFAULT 0, token_name TEXT, api_key TEXT,"
"key_locked INTEGER DEFAULT 0,chat_key_locked INTEGER DEFAULT 0);"
"INSERT INTO users(tg_id,username,token_name) VALUES(101,'one','tg101'),(202,'two','tg202');")
with closing(sqlite3.connect(self.gateway)) as con, con:
con.executescript("CREATE TABLE tokens(id INTEGER PRIMARY KEY, name TEXT,key TEXT,status INTEGER,"
"remain_quota INTEGER,unlimited_quota INTEGER,deleted_at INTEGER);"
"INSERT INTO tokens VALUES(1,'tg101','one',1,777,0,NULL),(2,'tg202','two',1,888,0,NULL);"
"CREATE TABLE users(username TEXT,status INTEGER);"
"INSERT INTO users VALUES('tg101',1),('tg202',1);")
with closing(sqlite3.connect(self.skin)) as con, con:
con.executescript("CREATE TABLE ip_claims(token_name TEXT);INSERT INTO ip_claims VALUES('tg101'),('tg202');")
self.env = patch.dict(os.environ, {"IISHKO_SKIN_DB": self.skin}, clear=True)
self.env.start()
self.addCleanup(self.env.stop)
for name, value in (("BOT_DB", self.bot), ("GW_DB", self.gateway), ("SKIN_DB", self.skin), ("PROTECT", ())):
item = patch.object(entry_autoban, name, value)
item.start()
self.addCleanup(item.stop)
def rows(self, path, sql):
with closing(sqlite3.connect(path)) as con:
return con.execute(sql).fetchall()
def test_empty_environment_disables_automatic_sanctions_and_delivery(self):
self.assertFalse(entry_autoban.enabled())
self.assertFalse(delivery_enabled())
self.assertEqual(entry_autoban.ban_cluster([101], reason="automatic_signal"), [])
self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens"), [(1, 777), (1, 888)])
def test_shared_public_ip_is_only_a_review_signal_even_if_legacy_flag_is_enabled(self):
os.environ["IISHKO_ENTRY_AUTOBAN"] = "1"
telemetry = EntryTelemetry(self.bot, b"offline-test-secret", [999], clock=lambda: 100000)
telemetry.init_db()
telemetry.record(101, "8.8.4.4")
telemetry.record(202, "8.8.4.4")
self.assertEqual(self.rows(self.bot, "SELECT banned FROM users ORDER BY tg_id"), [(0,), (0,)])
self.assertEqual(self.rows(self.gateway, "SELECT status,remain_quota FROM tokens ORDER BY id"), [(1, 777), (1, 888)])
self.assertEqual(self.rows(self.gateway, "SELECT status FROM users"), [(1,), (1,)])
self.assertEqual(self.rows(self.skin, "SELECT COUNT(*) FROM ip_claims"), [(2,)])
self.assertEqual(self.rows(self.bot, "SELECT COUNT(*) FROM wa_entry_alerts"), [(1,)])
claim = telemetry.claim()
self.assertIsNotNone(claim)
self.assertIn("не применяется", notification_text(claim))
self.assertFalse(entry_autoban.ban_user(101))
self.assertEqual(entry_autoban.ban_cluster([101, 202]), [])
def test_explicit_admin_moderation_is_not_disabled_by_safe_automatic_default(self):
with patch.object(entry_autoban, "ban_user", return_value=True) as ban:
self.assertEqual(entry_autoban.ban_cluster([101, 101], reason="admin_button"), [101])
ban.assert_called_once_with(101, "admin_button")
def test_unified_custom_skin_path_is_used_for_actual_ip_claim_cleanup(self):
tree = ast.parse((ROOT / "bot/grok_bot.py").read_text(encoding="utf-8"))
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_full_ban")
ns = {"sqlite3": sqlite3, "Path": Path, "skin_db_path": skin_db_path,
"BOT_DB": self.bot, "log": logging.getLogger("offline-cleanup"), "_newapi_exec": Mock()}
exec(compile(ast.Module(body=[function], type_ignores=[]), "real-full-ban", "exec"), ns)
ns["_full_ban"](101, "tg101", "admin_button")
self.assertEqual(self.rows(self.skin, "SELECT token_name FROM ip_claims"), [("tg202",)])
# The gateway uses the same resolver, not a second hardcoded fallback.
tree = ast.parse((ROOT / "gateway/grok-web-skin.py").read_text(encoding="utf-8"))
assignment = next(node for node in tree.body if isinstance(node, ast.Assign)
and any(isinstance(target, ast.Name) and target.id == "TG_PROVISION_DB" for target in node.targets))
ns = {"skin_db_path": skin_db_path}
exec(compile(ast.Module(body=[assignment], type_ignores=[]), "gateway-path", "exec"), ns)
self.assertEqual(ns["TG_PROVISION_DB"], self.skin)
def test_notification_opt_in_and_kill_switches(self):
for value in ("0", "", "false", "no", "off", "unexpected"):
with self.subTest(value=value), patch.dict(os.environ, {"IISHKO_NOTIFICATIONS_ENABLED": value}):
self.assertFalse(delivery_enabled())
os.environ["IISHKO_NOTIFICATIONS_ENABLED"] = "1"
self.assertTrue(delivery_enabled())
os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "0"
self.assertFalse(delivery_enabled())
os.environ["IISHKO_ENTRY_DELIVERY_ENABLED"] = "1"
os.environ["IISHKO_SUPPORT_DELIVERY_ENABLED"] = "0"
self.assertFalse(delivery_enabled())
if __name__ == "__main__":
unittest.main()