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

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

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

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

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

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

350 lines
16 KiB
Python

"""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()