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.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
"""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()
|
||||
@@ -524,7 +524,7 @@ class AccountAdminUnbanTests(unittest.TestCase):
|
||||
self.assertEqual(self.token(1)["status"], 2)
|
||||
self.assert_finance(finance)
|
||||
# The same receipt is read by entry autoban in the bot database.
|
||||
self.assertFalse(entry_autoban.ban_user(101))
|
||||
self.assertFalse(entry_autoban.ban_user(101, reason="admin_button"))
|
||||
self.assert_finance(finance)
|
||||
|
||||
def test_manual_unban_receipt_is_bot_scoped_and_explicit_ban_revokes_it(self):
|
||||
|
||||
@@ -49,6 +49,7 @@ class AccountBalancesTests(unittest.TestCase):
|
||||
tree = ast.parse((ROOT/'bot/webapp/mk_daemon.py').read_text(encoding='utf-8'))
|
||||
functions = [node for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))]
|
||||
self.ns = dict(globals(), BOT_DB=self.bot, GW_DB=self.gw, Q=500000,
|
||||
econ_state_path=lambda: str(Path(temp.name) / 'econ_state.json'),
|
||||
g=SimpleNamespace(MK_CAP={1:4},badge_of=lambda uid:1,KEY_WAIT_SEC=86400))
|
||||
exec(compile(ast.Module(body=functions,type_ignores=[]), 'isolated-key-daemon', 'exec'), self.ns)
|
||||
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
"""Deploy/docs contract: every documented unit path must resolve inside this repo.
|
||||
|
||||
The tests are static: they parse the files shipped under ``deploy/`` and the two
|
||||
operator-facing docs. Nothing here starts a service, imports runtime code or
|
||||
touches the network.
|
||||
|
||||
Mapping source of truth is the table in ``deploy/README.md``; the four core
|
||||
units under ``deploy/systemd/`` are checked against it. Services this repository
|
||||
does not implement (healthcheck, alert-watch, media adapter, firewall) ship
|
||||
nothing at all: no units, no templates, no stubs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
DEPLOY = REPO_ROOT / "deploy"
|
||||
SYSTEMD = DEPLOY / "systemd"
|
||||
CADDY = DEPLOY / "caddy" / "Caddyfile.example"
|
||||
DEPLOY_README = DEPLOY / "README.md"
|
||||
RUNTIME_ENV = DEPLOY / "runtime.env.example"
|
||||
CONTRIBUTING = REPO_ROOT / "CONTRIBUTING.md"
|
||||
SECURITY = REPO_ROOT / "SECURITY.md"
|
||||
|
||||
# Units that must exist: the first-party services this repo can actually run.
|
||||
CORE_UNITS = {
|
||||
"grok-bot.service": "bot",
|
||||
"iishko-webapp.service": "miniapp",
|
||||
"grok-web-skin.service": "gateway",
|
||||
"iishko-moderation.service": None, # native binary, not run through run.py
|
||||
}
|
||||
|
||||
# Scripts that do not exist in this repository; they belong to the operator.
|
||||
ABSENT_EXTERNAL_SCRIPTS = (
|
||||
"grok-healthcheck.py",
|
||||
"grok-alert-watch.py",
|
||||
"media_tts.py",
|
||||
"iishko-fw.sh",
|
||||
"/usr/local/sbin/iishko-fw",
|
||||
"zai_shim.caddy",
|
||||
)
|
||||
|
||||
# ``scripts/run.py`` is the shared bootstrap; it is part of the repo contract and
|
||||
# is referenced by every core target unit. If it is missing from a checkout the
|
||||
# units still point at a documented location, so the path check allows it only
|
||||
# when deploy/README.md documents it as the launcher.
|
||||
BOOTSTRAP_REL = "scripts/run.py"
|
||||
|
||||
# Host paths are absolute, so anchoring on "/" keeps the target table (also
|
||||
# backticked) from being parsed as mapping rows across line breaks.
|
||||
MAPPING_ROW = re.compile(r"^\|\s*`(?P<host>/[^`]+)`\s*\|\s*(?P<source>[^|]*)\|\s*(?P<kind>[^|]*)\|", re.M)
|
||||
TARGET_ROW = re.compile(r"^\|\s*`(?P<target>[a-z]+)`\s*\|\s*`(?P<module>[^`]+)`", re.M)
|
||||
|
||||
|
||||
def read(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8", errors="replace")
|
||||
|
||||
|
||||
def mapping() -> dict[str, tuple[str, str]]:
|
||||
"""host path -> (repo source description, kind)."""
|
||||
rows = {}
|
||||
for match in MAPPING_ROW.finditer(read(DEPLOY_README)):
|
||||
rows[match.group("host").strip()] = (match.group("source").strip(), match.group("kind").strip())
|
||||
return rows
|
||||
|
||||
|
||||
def targets() -> dict[str, str]:
|
||||
"""run.py target -> repo module."""
|
||||
return {m.group("target"): m.group("module").strip() for m in TARGET_ROW.finditer(read(DEPLOY_README))}
|
||||
|
||||
|
||||
def unit_directives(path: Path) -> list[tuple[str, str]]:
|
||||
out = []
|
||||
for line in read(path).splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith(("#", ";", "[")):
|
||||
continue
|
||||
if "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
out.append((key.strip(), value.strip()))
|
||||
return out
|
||||
|
||||
|
||||
def exec_paths(value: str) -> list[str]:
|
||||
"""Absolute filesystem paths from an ExecStart line (argv[0] + path args)."""
|
||||
try:
|
||||
argv = shlex.split(value)
|
||||
except ValueError:
|
||||
argv = value.split()
|
||||
paths = []
|
||||
for arg in argv:
|
||||
if arg.startswith(("-", "@", "+", "!", ":")):
|
||||
arg = arg.lstrip('-@+!:')
|
||||
if arg.startswith("/") and "$" not in arg:
|
||||
paths.append(arg)
|
||||
return paths
|
||||
|
||||
|
||||
def map_to_repo(host_path: str, table: dict[str, tuple[str, str]]) -> str | None:
|
||||
"""Translate a host path into a repo-relative path using the mapping table."""
|
||||
for host, (_source, _kind) in sorted(table.items(), key=lambda kv: -len(kv[0])):
|
||||
host = host.rstrip("/")
|
||||
if host_path == host:
|
||||
return "."
|
||||
if host_path.startswith(host + "/"):
|
||||
return host_path[len(host) + 1 :]
|
||||
return None
|
||||
|
||||
|
||||
class DeployMappingTest(unittest.TestCase):
|
||||
def test_mapping_table_is_documented(self):
|
||||
table = mapping()
|
||||
self.assertIn("/opt/iishko", table, "deploy/README.md must document the repo root mapping")
|
||||
self.assertIn("/etc/iishko/runtime.env", table, "runtime env file must be documented")
|
||||
kind = table["/opt/iishko"][1].lower()
|
||||
self.assertTrue("дерево" in kind or "tree" in kind, "repo root mapping must be documented as a tree")
|
||||
|
||||
def test_core_unit_execstart_paths_resolve(self):
|
||||
table = mapping()
|
||||
self.assertTrue(table, "mapping table is unreadable")
|
||||
deploy_doc = read(DEPLOY_README)
|
||||
for unit in sorted(SYSTEMD.glob("*.service")):
|
||||
for key, value in unit_directives(unit):
|
||||
if key != "ExecStart":
|
||||
continue
|
||||
paths = exec_paths(value)
|
||||
self.assertTrue(paths, f"{unit.name}: ExecStart has no absolute path: {value}")
|
||||
for host_path in paths:
|
||||
if host_path == "/etc/iishko/runtime.env":
|
||||
# Server-side config: seeded from deploy/runtime.env.example.
|
||||
self.assertIn("/etc/iishko/runtime.env", table)
|
||||
continue
|
||||
rel = map_to_repo(host_path, table)
|
||||
self.assertIsNotNone(rel, f"{unit.name}: {host_path} is outside the documented mapping")
|
||||
if rel.startswith(".venv/"):
|
||||
# Generated on the host, documented as such.
|
||||
self.assertIn(".venv", deploy_doc)
|
||||
self.assertIn("venv", deploy_doc.lower())
|
||||
continue
|
||||
if rel == BOOTSTRAP_REL:
|
||||
# Shared bootstrap: documented, may be provided separately.
|
||||
self.assertIn(BOOTSTRAP_REL, deploy_doc)
|
||||
self.assertTrue(
|
||||
(REPO_ROOT / BOOTSTRAP_REL).is_file(),
|
||||
"scripts/run.py is documented as the launcher but missing from this checkout",
|
||||
)
|
||||
continue
|
||||
if rel == "bin/iishko-moderation":
|
||||
self.assertTrue(
|
||||
(REPO_ROOT / "moderation").is_dir(),
|
||||
"moderation/ must exist to build bin/iishko-moderation",
|
||||
)
|
||||
continue
|
||||
self.assertTrue(
|
||||
(REPO_ROOT / rel).exists(),
|
||||
f"{unit.name}: {host_path} maps to missing {rel}",
|
||||
)
|
||||
|
||||
def test_core_units_use_bootstrap_and_required_env_file(self):
|
||||
for name, target in CORE_UNITS.items():
|
||||
path = SYSTEMD / name
|
||||
self.assertTrue(path.is_file(), f"missing core unit {name}")
|
||||
directives = dict(unit_directives(path))
|
||||
self.assertEqual(directives.get("WorkingDirectory"), "/opt/iishko", f"{name}: wrong WorkingDirectory")
|
||||
if target:
|
||||
execstart = directives.get("ExecStart", "")
|
||||
self.assertIn(f"/{BOOTSTRAP_REL} {target}", execstart, f"{name}: must start via scripts/run.py {target}")
|
||||
self.assertIn("--env-file /etc/iishko/runtime.env", execstart, f"{name}: runtime env file not passed")
|
||||
else:
|
||||
self.assertIn("/opt/iishko/bin/iishko-moderation", directives.get("ExecStart", ""), f"{name}: binary path")
|
||||
self.assertEqual(
|
||||
directives.get("EnvironmentFile"),
|
||||
"/etc/iishko/runtime.env",
|
||||
f"{name}: EnvironmentFile must be present and not optional ('-' prefix)",
|
||||
)
|
||||
|
||||
def test_run_targets_exist_in_repo(self):
|
||||
table_targets = targets()
|
||||
for target in ("bot", "miniapp", "gateway"):
|
||||
self.assertIn(target, table_targets, f"deploy/README.md must document run.py target {target}")
|
||||
module = table_targets[target]
|
||||
self.assertTrue((REPO_ROOT / module).is_file(), f"target {target} points at missing {module}")
|
||||
|
||||
def test_docs_state_the_launcher_semantics(self):
|
||||
text = read(DEPLOY_README)
|
||||
self.assertIn(BOOTSTRAP_REL, text)
|
||||
self.assertIn("bot/iishko_bot.py", text)
|
||||
self.assertIn("bot/grok_bot.py", text)
|
||||
self.assertIn("--check", text)
|
||||
|
||||
def test_canonical_resolver_matches_documented_order(self):
|
||||
module = REPO_ROOT / "bot" / "runtime_config.py"
|
||||
self.assertTrue(module.is_file(), "deploy/README.md points at bot/runtime_config.py, which is missing")
|
||||
body = read(module)
|
||||
for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG", "IISHKO_SKIN_DB", "GATE_TG_DB"):
|
||||
self.assertIn(name, body, f"bot/runtime_config.py must resolve {name}")
|
||||
# Documented precedence: canonical name wins over the legacy alias.
|
||||
order = [body.index(name) for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")]
|
||||
self.assertEqual(
|
||||
order, sorted(order), "bot config precedence in runtime_config.py differs from deploy/README.md"
|
||||
)
|
||||
self.assertLess(body.index("IISHKO_SKIN_DB"), body.index("GATE_TG_DB"))
|
||||
|
||||
|
||||
class DeployScopeTest(unittest.TestCase):
|
||||
def test_no_external_script_in_core_units(self):
|
||||
for unit in SYSTEMD.glob("*"):
|
||||
body = read(unit)
|
||||
for absent in ABSENT_EXTERNAL_SCRIPTS:
|
||||
self.assertNotIn(absent, body, f"{unit.name} references absent {absent}")
|
||||
|
||||
def test_core_dir_has_no_templates(self):
|
||||
for item in SYSTEMD.iterdir():
|
||||
self.assertFalse(item.name.endswith(".example"), f"{item.name} is a template, not a unit")
|
||||
self.assertEqual(set(CORE_UNITS), {p.name for p in SYSTEMD.glob("*.service")})
|
||||
|
||||
def test_no_external_template_graveyard(self):
|
||||
"""Dead templates were removed: no directory may hold units the repo cannot run."""
|
||||
self.assertFalse((DEPLOY / "external").exists(), "deploy/external must stay removed")
|
||||
self.assertEqual(
|
||||
{"systemd", "caddy"}, {p.name for p in DEPLOY.iterdir() if p.is_dir()},
|
||||
"deploy/ grew an undocumented subdirectory",
|
||||
)
|
||||
for path in DEPLOY.rglob("*.service*"):
|
||||
self.assertIn(path.parent, (SYSTEMD,), f"{path} ships a unit outside systemd/")
|
||||
self.assertIn(path.name, CORE_UNITS, f"{path.name} has no implementation in this repo")
|
||||
|
||||
def test_readme_states_services_are_out_of_scope(self):
|
||||
text = read(DEPLOY_README).lower()
|
||||
for absent in ("healthcheck", "alert", "media", "firewall"):
|
||||
self.assertIn(absent, text, f"deploy/README.md must say {absent} is not included")
|
||||
self.assertNotIn("external/", text, "deploy/README.md still points at the removed template dir")
|
||||
self.assertNotIn("template only", text, "deploy/README.md still announces template files")
|
||||
|
||||
|
||||
class CaddyTest(unittest.TestCase):
|
||||
def test_imports_resolve_inside_repo(self):
|
||||
body = read(CADDY)
|
||||
defined = set(re.findall(r"\((\w+)\)\s*\{", body))
|
||||
for name in re.findall(r"^\s*import\s+(\S+)", body, re.M):
|
||||
if name.startswith(("http://", "https://")):
|
||||
continue
|
||||
if name in defined:
|
||||
continue
|
||||
candidates = [DEPLOY / "caddy" / name, DEPLOY / "caddy" / f"{name}.caddy"]
|
||||
self.assertTrue(
|
||||
any(candidate.is_file() for candidate in candidates),
|
||||
f"Caddyfile imports {name}, which is neither an inline snippet nor a file in deploy/caddy/",
|
||||
)
|
||||
|
||||
def test_no_absent_media_service_route(self):
|
||||
body = read(CADDY)
|
||||
active = "\n".join(line for line in body.splitlines() if not line.strip().startswith("#"))
|
||||
self.assertNotIn("127.0.0.1:8000", active, "Caddyfile must not route to the absent media adapter")
|
||||
self.assertNotIn("zai_shim", body)
|
||||
self.assertIn("reverse_proxy 127.0.0.1:48001", active)
|
||||
self.assertIn("reverse_proxy 127.0.0.1:8850", active)
|
||||
|
||||
|
||||
class DocsTest(unittest.TestCase):
|
||||
def test_contributing_has_no_symlink_lie(self):
|
||||
text = read(CONTRIBUTING).lower()
|
||||
for forbidden in ("symlink", "симлинк", "120000"):
|
||||
self.assertNotIn(forbidden, text, f"CONTRIBUTING.md still claims a symlink ({forbidden})")
|
||||
|
||||
def test_contributing_does_not_instruct_copying_modules(self):
|
||||
text = read(CONTRIBUTING)
|
||||
for pattern in (r"cp\s+bot/iishko_bot\.py", r"cp\s+bot/grok_bot\.py", r"copying the real module"):
|
||||
self.assertIsNone(re.search(pattern, text, re.I), f"CONTRIBUTING.md still recommends {pattern}")
|
||||
|
||||
def test_contributing_points_at_real_launcher_and_tests(self):
|
||||
text = read(CONTRIBUTING)
|
||||
self.assertIn(f"python {BOOTSTRAP_REL} bot", text)
|
||||
self.assertIn("bot/grok_bot.py", text)
|
||||
self.assertIn("bot/iishko_bot.py", text)
|
||||
self.assertIn("pytest", text)
|
||||
self.assertNotIn("их почти нет", text)
|
||||
|
||||
def test_no_placeholder_maintainer_handle(self):
|
||||
for doc in (CONTRIBUTING, SECURITY):
|
||||
text = read(doc)
|
||||
self.assertNotIn("@your-handle", text, f"{doc.name} still has a placeholder handle")
|
||||
self.assertIsNone(
|
||||
re.search(r"(?<![\w./])@[A-Za-z][A-Za-z0-9_]{4,}", text),
|
||||
f"{doc.name} invents a private contact handle",
|
||||
)
|
||||
|
||||
def test_security_promises_no_sla(self):
|
||||
text = read(SECURITY).lower()
|
||||
for claim in ("72", "48 час", "в течение суток", "sla", "гарантируем ответ"):
|
||||
self.assertNotIn(claim, text, f"SECURITY.md promises an unsupported response time ({claim})")
|
||||
|
||||
def test_security_has_no_fake_disclosure_endpoint(self):
|
||||
text = read(SECURITY)
|
||||
self.assertIn("профил", text.lower())
|
||||
self.assertNotIn("mailto:", text)
|
||||
self.assertIsNone(re.search(r"https?://", text), "SECURITY.md must not point at an unverified disclosure URL")
|
||||
|
||||
|
||||
class RuntimeEnvTest(unittest.TestCase):
|
||||
def test_example_env_has_no_secrets(self):
|
||||
self.assertTrue(RUNTIME_ENV.is_file())
|
||||
text = read(RUNTIME_ENV)
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
value = value.strip().strip('"').strip("'")
|
||||
self.assertNotRegex(value, r"^sk-[A-Za-z0-9_-]{8,}", f"{key}: looks like a real API key")
|
||||
self.assertNotRegex(value, r"^[0-9a-fA-F]{32,}$", f"{key}: looks like a real secret")
|
||||
self.assertNotRegex(value, r"^\d{8,10}:[A-Za-z0-9_-]{30,}$", f"{key}: looks like a real bot token")
|
||||
if "TOKEN" in key.upper():
|
||||
self.assertIn("REPLACE_ME", value, f"{key}: token placeholder must stay a placeholder")
|
||||
|
||||
def test_runtime_env_is_not_committed(self):
|
||||
self.assertFalse((REPO_ROOT / "runtime.env").exists(), "runtime.env must never be committed")
|
||||
self.assertFalse((REPO_ROOT / ".env").exists(), ".env must never be committed")
|
||||
gitignore = read(REPO_ROOT / ".gitignore")
|
||||
self.assertIn("runtime.env", gitignore)
|
||||
|
||||
def test_sid_secret_file_stays_outside_repo(self):
|
||||
text = read(RUNTIME_ENV)
|
||||
self.assertIn("TG_SID_SECRET_FILE", text, "runtime.env.example must document the session secret file")
|
||||
value = ""
|
||||
for line in text.splitlines():
|
||||
if line.strip().startswith("TG_SID_SECRET_FILE="):
|
||||
value = line.split("=", 1)[1].strip()
|
||||
self.assertTrue(value.startswith("/"), "secret file must be an absolute operator path, not repo-relative")
|
||||
self.assertNotIn(".local/tg-sid-secret", read(REPO_ROOT / ".gitignore"))
|
||||
self.assertIn("0600", text)
|
||||
self.assertIn("gateway service user", text)
|
||||
self.assertNotIn("> FILE", text, "shell redirection can create a 0644 session secret")
|
||||
|
||||
def test_documented_env_names_match_example(self):
|
||||
text = read(RUNTIME_ENV)
|
||||
for name in ("GROK_BOT_CFG", "IISHKO_SKIN_DB", "IISHKO_UPSTREAM", "IISHKO_MODERATION_TOKEN"):
|
||||
self.assertIn(name, text, f"runtime.env.example must define {name}")
|
||||
deploy_doc = read(DEPLOY_README)
|
||||
for alias in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG"):
|
||||
self.assertIn(alias, deploy_doc, f"deploy/README.md must document config alias {alias}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Shared IP is a signal, not a sanction: autoban is opt-in (IISHKO_ENTRY_AUTOBAN=1)."""
|
||||
"""Shared IP remains an operator signal even when legacy enforcement is enabled."""
|
||||
from contextlib import closing
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -66,11 +66,12 @@ class NatUsersTest(unittest.TestCase):
|
||||
self.assertEqual(banned, [(0,), (0,)])
|
||||
self.assertEqual(alerts, 1) # operator still gets the signal
|
||||
|
||||
def test_opt_in_enforces(self):
|
||||
def test_opt_in_still_keeps_shared_ip_access_and_quota(self):
|
||||
with mock.patch.dict(os.environ, {"IISHKO_ENTRY_AUTOBAN": "1"}):
|
||||
tokens, banned, _ = self._visit_both()
|
||||
self.assertEqual(tokens, [(2, 0), (2, 0)])
|
||||
self.assertEqual(banned, [(1,), (1,)])
|
||||
tokens, banned, alerts = self._visit_both()
|
||||
self.assertEqual(tokens, [(1, 5000), (1, 5000)])
|
||||
self.assertEqual(banned, [(0,), (0,)])
|
||||
self.assertEqual(alerts, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Office-извлечение: обычные файлы, битые архивы и пределы распаковки.
|
||||
|
||||
ZIP раздувает вход: 8 МБ .pptx распаковываются в сотни МБ. Тесты проверяют,
|
||||
что читаются фактические байты, а не объявленный размер, что лимит общий на
|
||||
архив, что чтение идёт кусками и что ранний выход срабатывает, когда текста уже
|
||||
достаточно. Никаких гигантских файлов: лимиты подменяются на маленькие.
|
||||
"""
|
||||
import importlib
|
||||
import io
|
||||
import sys
|
||||
import unittest
|
||||
import warnings
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
BOT = Path(__file__).resolve().parents[1] / "bot"
|
||||
sys.path.insert(0, str(BOT))
|
||||
file_intake = importlib.import_module("file_intake")
|
||||
extract = file_intake.extract
|
||||
_OfficeBudget = file_intake._OfficeBudget
|
||||
|
||||
|
||||
def _zip_bytes(entries) -> bytes:
|
||||
"""Собрать zip в памяти. `entries` — список пар (name, bytes); дубликаты разрешены."""
|
||||
buf = io.BytesIO()
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", UserWarning) # duplicate names are part of the scenario
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for name, data in entries:
|
||||
zf.writestr(name, data)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _docx_bytes(text: str = "Привет, мир") -> bytes:
|
||||
return _zip_bytes([
|
||||
("[Content_Types].xml", b"<Types/>"),
|
||||
("word/document.xml",
|
||||
f'<?xml version="1.0"?><w:document><w:body><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:body></w:document>'.encode()),
|
||||
])
|
||||
|
||||
|
||||
def _slide_body(text: str) -> bytes:
|
||||
return (
|
||||
'<?xml version="1.0"?><p:sld><p:cSld><p:spTree><p:sp><p:txBody>'
|
||||
f'<a:p><a:r><a:t>{text}</a:t></a:r></a:p>'
|
||||
'</p:txBody></p:sp></p:spTree></p:cSld></p:sld>'
|
||||
).encode()
|
||||
|
||||
|
||||
def _pptx_bytes(texts) -> bytes:
|
||||
entries = [("[Content_Types].xml", b"<Types/>")]
|
||||
for i, text in enumerate(texts, start=1):
|
||||
entries.append((f"ppt/slides/slide{i}.xml", _slide_body(text)))
|
||||
return _zip_bytes(entries)
|
||||
|
||||
|
||||
def _xlsx_bytes(shared, rows) -> bytes:
|
||||
items = "".join(f"<si><t>{s}</t></si>" for s in shared)
|
||||
cells = "".join(
|
||||
f'<c r="A{n}" t="s"><v>{idx}</v></c>' for n, idx in enumerate(rows, start=1)
|
||||
)
|
||||
sheet = (
|
||||
'<?xml version="1.0"?><worksheet><sheetData>'
|
||||
f'<row r="1">{cells}</row>'
|
||||
'</sheetData></worksheet>'
|
||||
).encode()
|
||||
return _zip_bytes([
|
||||
("[Content_Types].xml", b"<Types/>"),
|
||||
("xl/sharedStrings.xml", f"<sst>{items}</sst>".encode()),
|
||||
("xl/worksheets/sheet1.xml", sheet),
|
||||
])
|
||||
|
||||
|
||||
def _odt_bytes(paras) -> bytes:
|
||||
body = "".join(f"<text:p>{p}</text:p>" for p in paras)
|
||||
return _zip_bytes([
|
||||
("[Content_Types].xml", b"<Types/>"),
|
||||
("content.xml", f'<?xml version="1.0"?><office:document><office:body>{body}</office:body></office:document>'.encode()),
|
||||
])
|
||||
|
||||
|
||||
class _SpyZip:
|
||||
"""Прокси над ZipFile: считает открытия записей и запрошенные размеры read()."""
|
||||
|
||||
def __init__(self, zf: zipfile.ZipFile) -> None:
|
||||
self._zf = zf
|
||||
self.opened: list[str] = []
|
||||
self.read_sizes: list[int] = []
|
||||
|
||||
def namelist(self):
|
||||
return self._zf.namelist()
|
||||
|
||||
def infolist(self):
|
||||
return self._zf.infolist()
|
||||
|
||||
def getinfo(self, name):
|
||||
return self._zf.getinfo(name)
|
||||
|
||||
def open(self, name, *args, **kwargs):
|
||||
self.opened.append(name)
|
||||
raw = self._zf.open(name, *args, **kwargs)
|
||||
spy = self
|
||||
|
||||
class _File:
|
||||
def read(self, n=-1):
|
||||
spy.read_sizes.append(n)
|
||||
return raw.read(n)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
raw.close()
|
||||
return False
|
||||
|
||||
return _File()
|
||||
|
||||
|
||||
class _RecordingBudget(_OfficeBudget):
|
||||
"""Запоминает созданные читатели, чтобы проверить фактический объём распаковки."""
|
||||
|
||||
created: list = []
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
_RecordingBudget.created.append(self)
|
||||
|
||||
|
||||
class OfficeExtractionTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
_RecordingBudget.created = []
|
||||
|
||||
# --- normal extraction --------------------------------------------------
|
||||
|
||||
def test_docx_plain_text(self) -> None:
|
||||
res = extract("заметка.docx", _docx_bytes())
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertEqual(res.kind, "docx")
|
||||
self.assertIn("Привет, мир", res.text)
|
||||
self.assertFalse(res.truncated)
|
||||
self.assertEqual(res.chars, len(res.text))
|
||||
|
||||
def test_pptx_slides_order_and_labels(self) -> None:
|
||||
res = extract("deck.pptx", _pptx_bytes(["первый", "второй", "третий"]))
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertEqual(res.kind, "pptx")
|
||||
self.assertLess(res.text.index("первый"), res.text.index("второй"))
|
||||
self.assertLess(res.text.index("второй"), res.text.index("третий"))
|
||||
self.assertIn("slide1.xml", res.text)
|
||||
|
||||
def test_xlsx_shared_strings_resolved(self) -> None:
|
||||
res = extract("таблица.xlsx", _xlsx_bytes(["альфа", "бета"], [1, 0]))
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
line = [ln for ln in res.text.splitlines() if "\t" in ln][0]
|
||||
self.assertEqual(line.split("\t"), ["бета", "альфа"])
|
||||
|
||||
def test_odt_paragraphs(self) -> None:
|
||||
res = extract("док.odt", _odt_bytes(["первый абзац", "второй абзац"]))
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertEqual(res.kind, "odt")
|
||||
self.assertIn("первый абзац", res.text)
|
||||
self.assertIn("второй абзац", res.text)
|
||||
|
||||
# --- refusals -----------------------------------------------------------
|
||||
|
||||
def test_corrupt_archive_is_reported(self) -> None:
|
||||
res = extract("битый.pptx", b"PK\x03\x04 definitely not a real zip")
|
||||
self.assertFalse(res.ok)
|
||||
self.assertIn("повреждён", res.reason)
|
||||
|
||||
def test_broken_compressed_stream_is_reported(self) -> None:
|
||||
data = _pptx_bytes(["text"])
|
||||
errors = (EOFError("truncated compressed stream"),
|
||||
file_intake.zlib.error("invalid compressed stream"))
|
||||
for error in errors:
|
||||
with self.subTest(error=type(error).__name__):
|
||||
with mock.patch.object(zipfile.ZipFile, "open", side_effect=error):
|
||||
result = extract("broken.pptx", data)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertIn("повреждён", result.reason)
|
||||
|
||||
def test_zip_without_office_structure(self) -> None:
|
||||
data = _zip_bytes([("readme.txt", b"just a zip")])
|
||||
res = extract("файл.docx", data)
|
||||
self.assertFalse(res.ok)
|
||||
self.assertIn("без ожидаемой структуры", res.reason)
|
||||
|
||||
def test_upload_limit_unchanged(self) -> None:
|
||||
res = extract("big.docx", b"\0" * (file_intake.MAX_FILE_BYTES + 1))
|
||||
self.assertFalse(res.ok)
|
||||
self.assertIn("предел", res.reason)
|
||||
self.assertEqual(file_intake.MAX_FILE_BYTES, 8 * 1024 * 1024)
|
||||
|
||||
# --- decompression limits -----------------------------------------------
|
||||
|
||||
def test_entry_limit_bounds_actual_bytes(self) -> None:
|
||||
payload = ("слово " * 4000).encode() # ~24 KB of text, compresses well
|
||||
data = _zip_bytes([("word/document.xml", payload)])
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy, entry_limit=1000)
|
||||
text, clipped = reader.read_prefix("word/document.xml")
|
||||
self.assertTrue(clipped)
|
||||
self.assertLessEqual(reader.consumed, 1000)
|
||||
self.assertLessEqual(sum(spy.read_sizes), 1000) # bytes actually read
|
||||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||
self.assertNotIn(-1, spy.read_sizes)
|
||||
self.assertLessEqual(len(text), 1000)
|
||||
self.assertEqual(reader.entries_read, 1)
|
||||
self.assertTrue(reader.cut)
|
||||
self.assertTrue(reader.warnings)
|
||||
|
||||
def test_exact_cap_needs_no_lookahead(self) -> None:
|
||||
"""Ровно лимит байт: без досмотра лишнего байта, но помечается как обрезанное."""
|
||||
payload = b"a" * 1024
|
||||
data = _zip_bytes([("word/document.xml", payload)])
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy, entry_limit=1024, chunk=4096)
|
||||
text, clipped = reader.read_prefix("word/document.xml")
|
||||
self.assertEqual(spy.read_sizes, [1024]) # a single read, exactly the cap
|
||||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||
self.assertLessEqual(sum(spy.read_sizes), 1024)
|
||||
self.assertEqual(len(text), 1024)
|
||||
self.assertTrue(clipped) # an entry exactly at the cap is conservatively reported as cut
|
||||
self.assertTrue(reader.cut)
|
||||
|
||||
def test_entry_limit_does_not_trust_declared_size(self) -> None:
|
||||
# small input, large decompressed size: only real reads are charged
|
||||
payload = b"a" * 200_000
|
||||
data = _zip_bytes([("word/document.xml", payload)])
|
||||
self.assertLess(len(data), 5000)
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as zf:
|
||||
reader = _OfficeBudget(zf, entry_limit=5000)
|
||||
reader.read_prefix("word/document.xml")
|
||||
self.assertLessEqual(reader.consumed, 5000)
|
||||
|
||||
def test_total_budget_shared_across_entries(self) -> None:
|
||||
data = _zip_bytes([
|
||||
("ppt/slides/slide1.xml", b"x" * 5000),
|
||||
("ppt/slides/slide2.xml", b"x" * 5000),
|
||||
("ppt/slides/slide3.xml", b"x" * 5000),
|
||||
])
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy, entry_limit=5000, total_limit=12_000)
|
||||
for name in ("ppt/slides/slide1.xml", "ppt/slides/slide2.xml", "ppt/slides/slide3.xml"):
|
||||
reader.read_prefix(name)
|
||||
self.assertLessEqual(reader.consumed, 12_000)
|
||||
self.assertLessEqual(sum(spy.read_sizes), 12_000)
|
||||
self.assertEqual(sum(spy.read_sizes), reader.consumed)
|
||||
self.assertTrue(reader.cut)
|
||||
self.assertTrue(any("предел" in w for w in reader.warnings))
|
||||
|
||||
def test_entry_cap_bounds_actual_reads(self) -> None:
|
||||
"""Жёсткий предел на число записей: дальше лимита записи не открываются."""
|
||||
names = [f"part{i}.xml" for i in range(1, 21)]
|
||||
data = _zip_bytes([(n, b"<x>tiny</x>") for n in names])
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy, max_entries=5)
|
||||
for name in names[:8]:
|
||||
reader.read_prefix(name)
|
||||
self.assertEqual(reader.entries_read, 5)
|
||||
self.assertEqual(len(spy.opened), 5) # nothing is opened past the entry cap
|
||||
self.assertTrue(reader.cut)
|
||||
self.assertTrue(any("не читаются" in w for w in reader.warnings))
|
||||
|
||||
def test_reads_are_chunked(self) -> None:
|
||||
data = _zip_bytes([("word/document.xml", b"y" * 20_000)])
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy, entry_limit=20_000, chunk=1024)
|
||||
reader.read_prefix("word/document.xml")
|
||||
self.assertTrue(spy.read_sizes)
|
||||
self.assertNotIn(-1, spy.read_sizes) # never read a whole entry at once
|
||||
self.assertLessEqual(max(spy.read_sizes), 1024)
|
||||
self.assertGreater(len(spy.read_sizes), 1)
|
||||
|
||||
def test_slide_count_capped(self) -> None:
|
||||
texts = [f"слайд {i}" for i in range(1, 11)]
|
||||
with mock.patch.object(file_intake, "_OFFICE_MAX_SLIDES", 3):
|
||||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy)
|
||||
text = file_intake._from_pptx(reader)
|
||||
self.assertEqual(len(spy.opened), 3)
|
||||
self.assertIn("слайд 3", text)
|
||||
self.assertNotIn("слайд 4", text)
|
||||
self.assertTrue(any("прочитаны первые 3" in w for w in reader.warnings))
|
||||
|
||||
def test_slide_byte_limit(self) -> None:
|
||||
texts = ["текст " * 2000, "хвост"]
|
||||
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 400):
|
||||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||
reader = _OfficeBudget(real)
|
||||
file_intake._from_pptx(reader)
|
||||
self.assertLessEqual(reader.consumed, 800) # per-slide cap
|
||||
self.assertTrue(reader.cut)
|
||||
|
||||
def test_markup_heavy_slide_stays_bounded(self) -> None:
|
||||
markup = ('<a:p><a:r><a:rPr lang="ru-RU" sz="1800" b="1"/><a:t>'
|
||||
+ "i" * 50 + "</a:t></a:r></a:p>") * 200 # ~24 KB of markup, ~10 KB of text
|
||||
data = _zip_bytes([("ppt/slides/slide1.xml", markup.encode())])
|
||||
with mock.patch.object(file_intake, "_OFFICE_SLIDE_MAX_BYTES", 2000):
|
||||
res = extract("тяжёлый.pptx", data)
|
||||
self.assertTrue(res.truncated)
|
||||
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||||
self.assertTrue(res.warnings)
|
||||
|
||||
def test_early_stop_when_enough_text(self) -> None:
|
||||
texts = [f"слайд номер {i} " + "z" * 500 for i in range(1, 41)]
|
||||
with mock.patch.object(file_intake, "TEXT_BUDGET", 300):
|
||||
with zipfile.ZipFile(io.BytesIO(_pptx_bytes(texts))) as real:
|
||||
spy = _SpyZip(real)
|
||||
reader = _OfficeBudget(spy)
|
||||
res = file_intake._finish(
|
||||
file_intake._from_pptx(reader), "pptx", reader.warnings, cut=reader.cut,
|
||||
)
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertTrue(res.truncated)
|
||||
self.assertLess(len(spy.opened), len(texts)) # stops before the end
|
||||
self.assertLessEqual(len(res.text), 300)
|
||||
self.assertTrue(any("показаны не все слайды" in w for w in res.warnings))
|
||||
|
||||
def test_eight_compressible_slides_bounded(self) -> None:
|
||||
"""Исходный сценарий: 8 «плотных» слайдов. Объём ограничен байтами, не памятью."""
|
||||
texts = [("слайд " + "q" * 3000) for _ in range(8)]
|
||||
data = _pptx_bytes(texts)
|
||||
self.assertLess(len(data), 20_000) # small input
|
||||
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||||
res = extract("amplify.pptx", data)
|
||||
self.assertTrue(_RecordingBudget.created)
|
||||
reader = _RecordingBudget.created[-1]
|
||||
self.assertLessEqual(reader.consumed, file_intake._OFFICE_TOTAL_MAX_BYTES)
|
||||
self.assertLessEqual(len(res.text), file_intake.TEXT_BUDGET)
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
|
||||
def test_truncation_is_announced(self) -> None:
|
||||
data = _pptx_bytes(["а" * 5000, "б" * 5000, "в" * 5000, "г" * 5000, "д" * 5000, "е" * 5000])
|
||||
res = extract("long.pptx", data)
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertTrue(res.truncated)
|
||||
self.assertTrue(any("показаны первые" in w for w in res.warnings))
|
||||
|
||||
def test_duplicate_entry_read_once(self) -> None:
|
||||
data = _zip_bytes([
|
||||
("word/document.xml", "<w:document><w:p><w:t>старый</w:t></w:p></w:document>".encode()),
|
||||
("word/document.xml", "<w:document><w:p><w:t>новый</w:t></w:p></w:document>".encode()),
|
||||
])
|
||||
with mock.patch.object(file_intake, "_OfficeBudget", _RecordingBudget):
|
||||
res = extract("dubl.docx", data)
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
reader = _RecordingBudget.created[-1]
|
||||
self.assertEqual(reader.entries_read, 1)
|
||||
self.assertIn("новый", res.text)
|
||||
self.assertLessEqual(reader.consumed, len(data) * 8)
|
||||
|
||||
|
||||
# --- XLSX: one row must not inflate the text ------------------
|
||||
|
||||
def test_xlsx_reused_string_cannot_inflate_output(self) -> None:
|
||||
"""Одна короткая строка sharedStrings на 3000 ячеек не даёт длинный текст."""
|
||||
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||||
self.assertLess(len(data), 20_000) # small input
|
||||
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
reader = _OfficeBudget(real)
|
||||
text = file_intake._from_xlsx(reader)
|
||||
self.assertLessEqual(len(text), 600)
|
||||
self.assertTrue(any("ячейк" in w for w in reader.warnings))
|
||||
self.assertTrue(reader.cut)
|
||||
|
||||
def test_xlsx_amplification_marked_truncated(self) -> None:
|
||||
data = _xlsx_bytes(["z" * 40], [0] * 3000)
|
||||
self.assertLess(len(data), 20_000) # small input, thousands of cells
|
||||
with mock.patch.object(file_intake, "TEXT_BUDGET", 500):
|
||||
res = extract("широкая.xlsx", data)
|
||||
self.assertEqual(file_intake.TEXT_BUDGET, 500)
|
||||
self.assertTrue(res.ok, res.reason)
|
||||
self.assertTrue(res.truncated)
|
||||
self.assertLessEqual(len(res.text), 500)
|
||||
self.assertGreater(len(res.text), 100) # useful prefix survives
|
||||
self.assertTrue(res.warnings)
|
||||
|
||||
def test_xlsx_cell_count_capped(self) -> None:
|
||||
data = _xlsx_bytes(["z"], [0] * 3000)
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as real:
|
||||
reader = _OfficeBudget(real)
|
||||
text = file_intake._from_xlsx(reader)
|
||||
self.assertTrue(any(f"ячеек в строке больше {file_intake._MAX_XLSX_CELLS}" in w
|
||||
for w in reader.warnings))
|
||||
self.assertEqual(text.splitlines()[-1].count("\t") + 1, file_intake._MAX_XLSX_CELLS)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,4 +1,4 @@
|
||||
"""PPTX: many highly-compressible slides must not be decompressed past the budgets."""
|
||||
"""PPTX extraction stops on text and actual decompression budgets."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
import sys
|
||||
@@ -20,19 +20,36 @@ def _pptx(slides: int, text: str) -> bytes:
|
||||
|
||||
|
||||
class PptxBudgetTest(unittest.TestCase):
|
||||
def test_stops_reading_after_text_budget(self):
|
||||
data = _pptx(200, "x" * 5000)
|
||||
with mock.patch.object(file_intake, "_read_entry", wraps=file_intake._read_entry) as rd:
|
||||
res = file_intake.extract("deck.pptx", data)
|
||||
self.assertTrue(res.ok)
|
||||
self.assertTrue(res.truncated)
|
||||
self.assertLess(rd.call_count, 10)
|
||||
def _extract_with_budget(self, data, total_limit=None):
|
||||
readers = []
|
||||
original = file_intake._OfficeBudget
|
||||
|
||||
def test_total_unpacked_budget_rejects(self):
|
||||
data = _pptx(20, "<b/>" * 262144) # 20 MiB of markup, no text
|
||||
with mock.patch.object(file_intake, "_MAX_UNPACKED_BYTES", 8 * 1024 * 1024):
|
||||
res = file_intake.extract("deck.pptx", data)
|
||||
self.assertFalse(res.ok)
|
||||
def factory(zf):
|
||||
kwargs = {} if total_limit is None else {"total_limit": total_limit}
|
||||
reader = original(zf, **kwargs)
|
||||
readers.append(reader)
|
||||
return reader
|
||||
|
||||
with mock.patch.object(file_intake, "_OfficeBudget", side_effect=factory):
|
||||
result = file_intake.extract("deck.pptx", data)
|
||||
self.assertEqual(len(readers), 1)
|
||||
return result, readers[0]
|
||||
|
||||
def test_stops_reading_after_text_budget(self):
|
||||
result, reader = self._extract_with_budget(_pptx(200, "x" * 5000))
|
||||
self.assertTrue(result.ok)
|
||||
self.assertTrue(result.truncated)
|
||||
self.assertLess(reader.entries_read, 10)
|
||||
self.assertLessEqual(len(result.text), file_intake.TEXT_BUDGET)
|
||||
|
||||
def test_total_unpacked_budget_rejects_textless_archive(self):
|
||||
limit = 8 * 1024 * 1024
|
||||
result, reader = self._extract_with_budget(_pptx(20, "<b/>" * 262144), limit)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertTrue(result.truncated)
|
||||
self.assertEqual(reader.consumed, limit)
|
||||
self.assertLess(reader.entries_read, 20)
|
||||
self.assertTrue(result.warnings)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Bootstrap tests use temporary config files, not operator or production settings."""
|
||||
from contextlib import closing
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
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]
|
||||
spec = importlib.util.spec_from_file_location("runtime_launcher", ROOT / "scripts/run.py")
|
||||
assert spec is not None and spec.loader is not None
|
||||
launcher = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(launcher)
|
||||
sys.path.insert(0, str(ROOT / "bot"))
|
||||
runtime_config = __import__("runtime_config")
|
||||
|
||||
|
||||
class BootstrapTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
self.root = Path(tmp.name)
|
||||
(self.root / "bot").mkdir()
|
||||
(self.root / "gateway").mkdir()
|
||||
(self.root / "bot/webapp").mkdir()
|
||||
self.config = {"bot_token": "123456:offline-token", "main_key": "offline-main",
|
||||
"newapi_pass": "offline-password", "channel_username": "offline_channel",
|
||||
"bot_db": "./bot.db", "newapi_db": "./one-api.db",
|
||||
"newapi_url": "http://127.0.0.1:49100"}
|
||||
(self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8")
|
||||
with closing(sqlite3.connect(self.root / "one-api.db")) as con:
|
||||
con.execute("CREATE TABLE tokens(id INTEGER PRIMARY KEY)")
|
||||
con.commit()
|
||||
(self.root / ".env").write_text("IISHKO_SKIN_DB=./skin.db\n", encoding="utf-8")
|
||||
|
||||
def test_explicit_root_dotenv_loads_without_shell_or_interpolation(self):
|
||||
(self.root / ".env").write_text(
|
||||
'\ufeffGROK_BOT_CFG=./bot/config.json\nIISHKO_SKIN_DB="./skin with space.db"\n'
|
||||
'IISHKO_ENTRY_AUTOBAN=0 # comment\nOPAQUE="${SHELL_SECRET} $(nothing-executed)"\n', encoding="utf-8")
|
||||
env = launcher.prepare_environment(self.root, process={"SHELL_SECRET": "must-not-expand"})
|
||||
self.assertEqual(env["GROK_BOT_CFG"], str(self.root / "bot/config.json"))
|
||||
self.assertEqual(env["IISHKO_ENTRY_AUTOBAN"], "0")
|
||||
self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "skin with space.db"))
|
||||
self.assertEqual(env["GATE_TG_DB"], env["IISHKO_SKIN_DB"])
|
||||
self.assertEqual(env["OPAQUE"], "${SHELL_SECRET} $(nothing-executed)")
|
||||
self.assertEqual(launcher.check_configuration(env), [])
|
||||
|
||||
def test_real_environment_including_legacy_alias_beats_file(self):
|
||||
(self.root / ".env").write_text("IISHKO_SKIN_DB=./file.db\nIISHKO_NOTIFICATIONS_ENABLED=1\n", encoding="utf-8")
|
||||
env = launcher.prepare_environment(self.root, process={"GATE_TG_DB": "./service.db",
|
||||
"IISHKO_NOTIFICATIONS_ENABLED": "0"})
|
||||
self.assertEqual(env["IISHKO_SKIN_DB"], str(self.root / "service.db"))
|
||||
self.assertEqual(env["IISHKO_NOTIFICATIONS_ENABLED"], "0")
|
||||
env = launcher.prepare_environment(self.root, process={"IISHKO_SKIN_DB": "./canonical.db", "GATE_TG_DB": "./old.db"})
|
||||
self.assertEqual(env["GATE_TG_DB"], str(self.root / "canonical.db"))
|
||||
|
||||
def test_legacy_config_and_db_aliases_are_shared_across_components(self):
|
||||
env = launcher.prepare_environment(self.root, process={"GROK_BOT_CONFIG": "./bot/config.json",
|
||||
"GATE_NEWAPI_DB": "./one-api.db"})
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
self.assertEqual(runtime_config.bot_config_path(), env["GROK_BOT_CFG"])
|
||||
self.assertEqual(runtime_config.gateway_db_path(), env["IISHKO_GW_DB"])
|
||||
self.assertEqual(runtime_config.skin_db_path(), env["IISHKO_SKIN_DB"])
|
||||
self.assertEqual(env["GATE_BOT_CONFIG"], env["GROK_BOT_CFG"])
|
||||
self.assertEqual(env["GATE_NEWAPI_DB"], env["IISHKO_GW_DB"])
|
||||
|
||||
def test_no_parent_dotenv_discovery_and_explicit_missing_file_fails(self):
|
||||
(self.root / ".env").write_text("PARENT_ONLY=not-loaded\n", encoding="utf-8")
|
||||
child = self.root / "child"
|
||||
child.mkdir()
|
||||
self.assertNotIn("PARENT_ONLY", launcher.prepare_environment(child, process={}))
|
||||
with self.assertRaises(ValueError):
|
||||
launcher.prepare_environment(self.root, env_file="missing.env", process={})
|
||||
|
||||
def test_real_platform_module_separator_and_direct_legacy_fallback(self):
|
||||
env = launcher.prepare_environment(self.root, process={})
|
||||
self.assertIn(str(self.root / "bot"), env["PYTHONPATH"].split(os.pathsep))
|
||||
self.assertIn(str(self.root / "gateway"), env["PYTHONPATH"].split(os.pathsep))
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(runtime_config.skin_db_path(), "/opt/grok-web-skin-tg.db")
|
||||
self.assertFalse(runtime_config.notifications_enabled())
|
||||
with patch.dict(os.environ, {"GATE_TG_DB": "legacy.db"}, clear=True):
|
||||
self.assertEqual(runtime_config.skin_db_path(), "legacy.db")
|
||||
|
||||
def test_check_is_offline_and_never_starts_application(self):
|
||||
with patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=launcher.prepare_environment(self.root, process={})), patch.object(launcher.runpy, "run_path") as run, patch("sys.stdout", new_callable=io.StringIO) as out:
|
||||
self.assertEqual(launcher.main(["bot", "--check"]), 0)
|
||||
run.assert_not_called()
|
||||
self.assertIn("no app started", out.getvalue())
|
||||
|
||||
def test_normal_launch_receives_dotenv_paths_and_selected_entrypoint(self):
|
||||
env = launcher.prepare_environment(self.root, process={})
|
||||
old_cwd, old_path, old_argv = Path.cwd(), list(sys.path), list(sys.argv)
|
||||
try:
|
||||
with patch.dict(os.environ, {}, clear=True), patch.object(launcher, "ROOT", self.root), patch.object(launcher, "prepare_environment", return_value=env), patch.object(launcher.runpy, "run_path") as run:
|
||||
self.assertEqual(launcher.main(["miniapp"]), 0)
|
||||
run.assert_called_once_with(str(self.root / "bot/webapp/server.py"), run_name="__main__")
|
||||
self.assertEqual(os.environ["GROK_BOT_CONFIG"], str(self.root / "bot/config.json"))
|
||||
self.assertEqual(Path.cwd(), self.root)
|
||||
self.assertIn(str(self.root / "bot"), sys.path)
|
||||
finally:
|
||||
os.chdir(old_cwd)
|
||||
sys.path[:] = old_path
|
||||
sys.argv[:] = old_argv
|
||||
|
||||
def test_missing_config_and_placeholders_fail_without_leaking_values(self):
|
||||
config_path = self.root / "bot/config.json"
|
||||
config_path.write_text('{"bot_token":"REPLACE_ME_PRIVATE_VALUE"}', encoding="utf-8")
|
||||
errors = launcher.check_configuration(launcher.prepare_environment(self.root, process={}))
|
||||
self.assertTrue(errors)
|
||||
self.assertNotIn("PRIVATE_VALUE", str(errors))
|
||||
config_path.unlink()
|
||||
self.assertIn("missing", launcher.check_configuration(launcher.prepare_environment(self.root, process={}))[0])
|
||||
|
||||
def test_config_upstream_and_db_survive_without_explicit_env_overrides(self):
|
||||
env = launcher.prepare_environment(self.root, process={})
|
||||
self.assertEqual(env["IISHKO_UPSTREAM"], self.config["newapi_url"])
|
||||
self.assertEqual(env["NEWAPI_URL"], self.config["newapi_url"])
|
||||
self.assertEqual(env["IISHKO_GW_DB"], str(self.root / "one-api.db"))
|
||||
self.assertNotIn("TG_SID_SECRET_FILE", env)
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
resolved = runtime_config.effective_bot_config(self.config)
|
||||
self.assertEqual(resolved["newapi_url"], env["IISHKO_UPSTREAM"])
|
||||
self.assertEqual(resolved["newapi_db"], env["IISHKO_GW_DB"])
|
||||
|
||||
def test_env_secrets_override_config_for_validation_and_all_consumers(self):
|
||||
for key in ("bot_token", "newapi_pass"):
|
||||
self.config[key] = "REPLACE_ME_PRIVATE_VALUE"
|
||||
(self.root / "bot/config.json").write_text(json.dumps(self.config), encoding="utf-8")
|
||||
process = {"GROK_BOT_TOKEN": "123456:env-offline-token", "NEWAPI_PASS": "env-offline-password",
|
||||
"NEWAPI_URL": "http://127.0.0.1:49101", "TG_SID_SECRET_FILE": "./existing-secret"}
|
||||
env = launcher.prepare_environment(self.root, process=process)
|
||||
self.assertEqual(launcher.check_configuration(env), [])
|
||||
self.assertEqual(env["TG_SID_SECRET_FILE"], str(self.root / "existing-secret"))
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
resolved = runtime_config.effective_bot_config(self.config)
|
||||
self.assertEqual(resolved["bot_token"], process["GROK_BOT_TOKEN"])
|
||||
self.assertEqual(resolved["newapi_pass"], process["NEWAPI_PASS"])
|
||||
self.assertEqual(resolved["newapi_url"], process["NEWAPI_URL"])
|
||||
|
||||
def test_preflight_rejects_invalid_data_directories_without_creating_db(self):
|
||||
env = launcher.prepare_environment(self.root, process={})
|
||||
for key in ("IISHKO_BOT_DB", "IISHKO_SKIN_DB"):
|
||||
with self.subTest(key=key):
|
||||
changed = {**env, key: str(self.root / "missing-directory/new.db")}
|
||||
self.assertTrue(any(key in problem for problem in launcher.check_configuration(changed)))
|
||||
self.assertFalse(Path(changed[key]).exists())
|
||||
|
||||
def test_real_cli_reads_explicit_env_outside_repository_cwd(self):
|
||||
env_file = self.root / "runtime.env"
|
||||
env_file.write_text("\n".join((
|
||||
"GROK_BOT_CFG=" + (self.root / "bot/config.json").as_posix(),
|
||||
"IISHKO_GW_DB=" + (self.root / "one-api.db").as_posix(),
|
||||
"IISHKO_APP_ROOT=" + (self.root / "bot").as_posix(),
|
||||
"IISHKO_BOT_DB=" + (self.root / "bot.db").as_posix(),
|
||||
"IISHKO_SKIN_DB=" + (self.root / "skin.db").as_posix(),
|
||||
)), encoding="utf-8")
|
||||
process = {key: value for key, value in os.environ.items()
|
||||
if not key.startswith(("IISHKO_", "GATE_", "GROK_", "NEWAPI_", "TG_SID_"))}
|
||||
for component in launcher.COMPONENTS:
|
||||
with self.subTest(component=component):
|
||||
result = subprocess.run([sys.executable, str(ROOT / "scripts/run.py"), component,
|
||||
"--env-file", str(env_file), "--check"], cwd=self.root,
|
||||
env=process, capture_output=True, text=True, timeout=15)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("preflight passed", result.stdout)
|
||||
|
||||
def test_selfcheck_accepts_the_same_utf8_bom_config_as_entrypoints(self):
|
||||
sc_spec = importlib.util.spec_from_file_location("iishko_selfcheck", ROOT / "scripts/selfcheck.py")
|
||||
assert sc_spec is not None and sc_spec.loader is not None
|
||||
selfcheck = importlib.util.module_from_spec(sc_spec)
|
||||
sc_spec.loader.exec_module(selfcheck)
|
||||
config_path = self.root / "bot/config.json"
|
||||
config_path.write_text(json.dumps(self.config), encoding="utf-8-sig")
|
||||
self.assertEqual(config_path.read_bytes()[:3], b"\xef\xbb\xbf")
|
||||
problems, notes = [], []
|
||||
with patch.object(selfcheck, "ROOT", str(self.root)), \
|
||||
patch.dict(os.environ, {"GROK_BOT_CFG": str(config_path)}):
|
||||
selfcheck.check_config_templates(problems, notes)
|
||||
self.assertEqual(problems, [])
|
||||
self.assertFalse(any("bot config not found" in note for note in notes))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,281 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,470 @@
|
||||
"""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)
|
||||
Reference in New Issue
Block a user