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

133 lines
6.3 KiB
Python

"""Operator route checks are read-only unless an explicit apply is authorized."""
from contextlib import closing, redirect_stderr
import importlib.util
import io
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "bot" / "abilities_guard.py"
sys.path.insert(0, str(ROOT / "bot"))
class AbilitiesGuardCliTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.db = self.root / "gateway.db"
self.source = self.root / "catalog.py"
self.source.write_text('TIER_MODELS = {\n 1: ["basic"],\n 4: ["advanced"],\n}\n',
encoding="utf-8")
with closing(sqlite3.connect(self.db)) as con:
con.executescript('''
CREATE TABLE channels(id INTEGER PRIMARY KEY, status INTEGER, models TEXT);
CREATE TABLE abilities(channel_id INTEGER, model TEXT, "group" TEXT, enabled INTEGER);
CREATE TABLE tokens(id INTEGER PRIMARY KEY, status INTEGER, remain_quota INTEGER);
CREATE TABLE entry_autobans(uid INTEGER PRIMARY KEY, reason TEXT);
INSERT INTO channels VALUES(1,1,'basic, advanced'),(2,2,'basic'),(3,1,'other');
INSERT INTO abilities VALUES
(1,'basic','t1',0),(1,'advanced','t1',0),(1,'advanced','t4',0),
(1,'basic','default',0),(2,'basic','t1',0),(3,'basic','t1',0);
INSERT INTO tokens VALUES(1,1,5000);
INSERT INTO entry_autobans VALUES(101,'existing-receipt');
''')
self.env = {key: value for key, value in os.environ.items()
if not key.startswith(("IISHKO_", "GROK_", "GATE_", "NEWAPI_", "PYTHONPATH"))}
self.env.update(IISHKO_GW_DB=str(self.db), IISHKO_BOT_SOURCE=str(self.source))
def run_cli(self, *args):
return subprocess.run([sys.executable, str(SCRIPT), *map(str, args)],
cwd=self.root, env=self.env, capture_output=True,
text=True, encoding="utf-8", timeout=15)
def rows(self, table):
with closing(sqlite3.connect(self.db)) as con:
return con.execute("SELECT * FROM " + table).fetchall()
def test_default_is_read_only_with_no_database_changes(self):
before = self.db.read_bytes()
result = self.run_cli()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("mode=dry-run", result.stdout)
self.assertIn("re-enabled=0", result.stdout)
self.assertIn("dark=advanced,basic", result.stdout)
self.assertEqual(self.db.read_bytes(), before)
def test_apply_requires_both_explicit_paths_even_when_env_is_configured(self):
before = self.db.read_bytes()
for args in (("--apply",), ("--apply", "--db", self.db),
("--apply", "--source", self.source)):
with self.subTest(args=args):
result = self.run_cli(*args)
self.assertEqual(result.returncode, 2)
self.assertIn("--apply requires explicit --db and --source", result.stderr)
self.assertEqual(self.db.read_bytes(), before)
def test_missing_and_relative_paths_are_rejected_without_database_creation(self):
missing = self.root / "absent.db"
for args in (("--db", missing), ("--db", "gateway.db"),
("--source", "catalog.py"), ("--source", self.root / "absent.py")):
with self.subTest(args=args):
result = self.run_cli(*args)
self.assertEqual(result.returncode, 2)
self.assertIn("absolute path to an existing file", result.stderr)
self.assertFalse(missing.exists())
def test_empty_catalogue_does_not_touch_database(self):
self.source.write_text("TIER_MODELS = {}\n", encoding="utf-8")
before = self.db.read_bytes()
result = self.run_cli("--apply", "--db", self.db, "--source", self.source)
self.assertEqual(result.returncode, 1)
self.assertIn("no database changes made", result.stdout)
self.assertEqual(self.db.read_bytes(), before)
def test_apply_repairs_only_matching_live_tier_abilities(self):
tokens, receipts = self.rows("tokens"), self.rows("entry_autobans")
result = self.run_cli("--apply", "--db", self.db, "--source", self.source)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("mode=apply", result.stdout)
self.assertIn("re-enabled=3", result.stdout)
self.assertEqual([row[3] for row in self.rows("abilities")], [1, 0, 1, 1, 0, 0])
self.assertEqual(self.rows("tokens"), tokens)
self.assertEqual(self.rows("entry_autobans"), receipts)
repeated = self.run_cli("--apply", "--db", self.db, "--source", self.source)
self.assertEqual(repeated.returncode, 0, repeated.stderr)
self.assertIn("re-enabled=0", repeated.stdout)
def test_schema_failure_returns_nonzero_without_writing(self):
with closing(sqlite3.connect(self.db)) as con:
con.execute("DROP TABLE abilities")
con.commit()
before = self.db.read_bytes()
result = self.run_cli()
self.assertEqual(result.returncode, 2)
self.assertIn("Database check failed: OperationalError", result.stderr)
self.assertEqual(self.db.read_bytes(), before)
def test_apply_rolls_back_when_repair_fails(self):
spec = importlib.util.spec_from_file_location("abilities_guard_cli_probe", SCRIPT)
assert spec is not None and spec.loader is not None
guard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(guard)
before = self.rows("abilities")
def fail_after_write(con, tiers):
con.execute("UPDATE abilities SET enabled=1")
raise sqlite3.OperationalError("offline-injected-error")
with patch.object(guard, "repair_abilities", side_effect=fail_after_write), redirect_stderr(io.StringIO()):
code = guard.main(["--apply", "--db", str(self.db), "--source", str(self.source)])
self.assertEqual(code, 2)
self.assertEqual(self.rows("abilities"), before)
if __name__ == "__main__":
unittest.main()