feat(админка): independent admin_smoke и cron-строка без токена

This commit is contained in:
anor
2026-11-06 17:28:36 +10:00
parent f8c1e1a1d2
commit 732aedb796
6 changed files with 639 additions and 21 deletions
+265
View File
@@ -0,0 +1,265 @@
"""Проверки independent-пробы админки: без сети, на локальном HTTP-сервере.
Красный тест должен быть именно про то, что проба утверждает: версия, health,
оболочка, CSP. Не про «файл существует».
"""
import json
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
import admin_smoke # noqa: E402
def _server(version=200, health=200, admin=200, shell="legacy", csp="script-src 'self' 'unsafe-inline'", csp_header="Content-Security-Policy", body_override=None, csp2=None):
class H(BaseHTTPRequestHandler):
def log_message(self, *a): # noqa: D401 - тишина в тестах
return
def do_GET(self): # noqa: N802
if self.path == "/api/version":
self._send(version, json.dumps({"version": "2026-10-28b"}), "application/json")
elif self.path == "/health":
self._send(health, "ok", "text/plain")
elif self.path == "/admin":
if shell == "v2":
body = '<!doctype html><title>Админ-панель</title><div id="app"></div><script src="/static/admin2/app.js"></script>'
else:
body = body_override or '<!doctype html><title>Админ-панель</title><nav class="sidebar">Админ-панель</nav>'
self._send(admin, body, "text/html", csp, csp_header, csp2)
else:
self._send(404, "no", "text/plain")
def _send(self, code, body, ctype, csp=None, csp_header="Content-Security-Policy", csp2=None):
data = body.encode()
self.send_response(code)
self.send_header("Content-Type", ctype + "; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
if csp is not None:
self.send_header(csp_header, csp)
if csp2 is not None:
self.send_header(csp_header, csp2)
self.end_headers()
self.wfile.write(data)
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
@pytest.fixture
def base():
srv = _server()
yield f"http://127.0.0.1:{srv.server_port}"
srv.shutdown()
def test_legacy_ok(base):
r = admin_smoke.check(base)
assert r["ok"] is True
assert r["shell"] == "legacy"
assert r["version"] == "2026-10-28b"
assert r["csp_unsafe_inline"] is True # legacy имеет право
def test_v2_strict_csp_ok():
srv = _server(shell="v2", csp="default-src 'self'; script-src 'self'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is True
assert r["shell"] == "v2"
assert r["csp_unsafe_inline"] is False
finally:
srv.shutdown()
def test_v2_unsafe_inline_fails():
srv = _server(shell="v2", csp="script-src 'self' 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
assert r["checks"]["admin"] is True
finally:
srv.shutdown()
def test_legacy_id_app_in_script_is_not_v2():
body = ('<title>Админ-панель</title><nav class="sidebar"></nav>'
'<script>var x = \'<div id="app">\';</script>')
srv = _server(body_override=body)
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["shell"] == "legacy"
assert r["ok"] is True
finally:
srv.shutdown()
def test_v2_default_src_fallback_unsafe_fails():
srv = _server(shell="v2", csp="script-src-elem 'self'; default-src * 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_unknown_shell_fails():
srv = _server(body_override='<title>Админ-панель</title><p>no shell</p>')
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["shell"] == "unknown"
assert r["ok"] is False
assert r["checks"]["shell"] is False
finally:
srv.shutdown()
def test_v2_duplicate_script_src_first_wins_fails():
# По CSP первое вхождение директивы побеждает; unsafe-inline в первом — не строго.
srv = _server(shell="v2", csp="script-src 'unsafe-inline'; script-src 'self'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_v2_multiple_headers_intersection_passes():
# Две политики применяются совместно: вторая запрещает inline, значит inline запрещён.
srv = _server(shell="v2", csp="script-src 'unsafe-inline'", csp2="script-src 'self'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is True
assert r["checks"]["csp"] is True
finally:
srv.shutdown()
def test_v2_two_headers_both_unsafe_fails():
srv = _server(shell="v2", csp="script-src 'unsafe-inline'", csp2="script-src 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_v2_nonce_ignores_unsafe_inline():
srv = _server(shell="v2", csp="script-src 'nonce-abc' 'strict-dynamic' 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is True
assert r["checks"]["csp"] is True
finally:
srv.shutdown()
def test_multiple_errors_are_kept():
srv = _server(version=500, admin=500)
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert "version" in (r["error"] or "")
assert "admin" in (r["error"] or "")
finally:
srv.shutdown()
def test_v2_script_src_elem_unsafe_fails():
srv = _server(shell="v2", csp="script-src 'self'; script-src-elem 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_v2_script_src_attr_unsafe_fails():
srv = _server(shell="v2", csp="script-src 'self'; script-src-attr 'unsafe-inline'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_v2_header_without_script_policy_fails():
srv = _server(shell="v2", csp="frame-ancestors 'none'")
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["csp_present"] is True
assert r["csp_has_script_policy"] is False
assert r["checks"]["csp"] is False
finally:
srv.shutdown()
def test_v2_lowercase_header_is_seen():
srv = _server(shell="v2", csp="script-src 'self'", csp_header="content-security-policy")
try:
# send_header сохраняет регистр, но HTTPMessage ищет без него
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is True
assert r["csp_present"] is True
finally:
srv.shutdown()
def test_v2_missing_csp_fails():
srv = _server(shell="v2", csp=None)
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["csp"] is False
assert r["csp_present"] is False
finally:
srv.shutdown()
def test_broken_version_fails():
srv = _server(version=500)
try:
r = admin_smoke.check(f"http://127.0.0.1:{srv.server_port}")
assert r["ok"] is False
assert r["checks"]["version"] is False
finally:
srv.shutdown()
def test_state_write_failure_does_not_kill_output(base, tmp_path, capsys):
# /dev/null — файл, не каталог: mkdir родителя обязан упасть, но вывод и код остаются.
rc = admin_smoke.main(["--base-url", base, "--state", "/dev/null/x"])
out = capsys.readouterr().out
assert rc == 0
assert "state_error=" in out
assert "Traceback" not in out
def test_state_tmp_removed_on_success(base, tmp_path):
state = tmp_path / "s.state"
assert admin_smoke.main(["--base-url", base, "--state", str(state)]) == 0
assert state.exists()
assert list(tmp_path.glob("*.tmp")) == []
def test_state_written(base, tmp_path):
state = tmp_path / "admin_smoke.state"
rc = admin_smoke.main(["--base-url", base, "--state", str(state), "--json"])
assert rc == 0
data = json.loads(state.read_text(encoding="utf-8"))
assert data["ok"] is True
assert data["version"] == "2026-10-28b"
assert data["checks"]["admin"] is True
+89
View File
@@ -0,0 +1,89 @@
"""Установщик крона: идемпотентность, пустой crontab, отказ на путь с пробелом.
Fake `crontab`/`flock` в PATH: настоящий крон в тестах не трогаем.
"""
import os
import stat
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts" / "install_health_cron.sh"
def _fake_bin(tmp: Path) -> Path:
b = tmp / "bin"
b.mkdir()
cron_file = tmp / "crontab.txt"
(b / "crontab").write_text(
"#!/bin/bash\n"
'FILE="${CRON_FILE:?}"\n'
'if [ "${1:-}" = "-l" ]; then cat "$FILE" 2>/dev/null; exit $?; fi\n'
'if [ -f "${1:-}" ]; then cp "$1" "$FILE"; exit 0; fi\n'
'exit 2\n', encoding="utf-8")
(b / "flock").write_text("#!/bin/bash\nexit 0\n", encoding="utf-8")
for f in (b / "crontab", b / "flock"):
f.chmod(f.stat().st_mode | stat.S_IXUSR)
return b
def _app(tmp: Path, name="app") -> Path:
app = tmp / name
(app / "scripts").mkdir(parents=True)
(app / "health_checks.py").write_text("", encoding="utf-8")
(app / "scripts" / "admin_smoke.py").write_text("", encoding="utf-8")
return app
def _run(tmp: Path, app: Path, bin_dir: Path):
env = dict(os.environ)
env["HOME"] = str(tmp / "home")
env["CRON_FILE"] = str(tmp / "crontab.txt")
env["HEALTH_LOG"] = str(tmp / "health.log")
env["PATH"] = f"{bin_dir}:{env.get('PATH', '')}"
Path(env["HOME"]).mkdir(exist_ok=True)
return subprocess.run(["bash", str(SCRIPT), str(app)], env=env,
capture_output=True, text=True, timeout=30)
def test_install_is_idempotent(tmp_path):
b = _fake_bin(tmp_path)
app = _app(tmp_path)
r1 = _run(tmp_path, app, b)
assert r1.returncode == 0, r1.stderr
text = (tmp_path / "crontab.txt").read_text()
assert text.count("smeta-admin-smoke-app") == 1
assert text.count("smeta-health-quick-app") == 1
assert text.count("smeta-health-deep-app") == 1
r2 = _run(tmp_path, app, b)
assert r2.returncode == 0, r2.stderr
text = (tmp_path / "crontab.txt").read_text()
assert text.count("smeta-admin-smoke-app") == 1
assert len([ln for ln in text.splitlines() if ln.strip()]) == 3
def test_empty_crontab_is_norm_not_failure(tmp_path):
b = _fake_bin(tmp_path)
app = _app(tmp_path)
r = _run(tmp_path, app, b)
assert r.returncode == 0, r.stderr
assert "не откат" in r.stdout
assert "smeta-admin-smoke-app" in (tmp_path / "crontab.txt").read_text()
def test_path_with_space_rejected(tmp_path):
b = _fake_bin(tmp_path)
app = _app(tmp_path, "app space")
r = _run(tmp_path, app, b)
assert r.returncode == 1
assert "не поддерживается" in r.stderr
assert not (tmp_path / "crontab.txt").exists()
def test_missing_admin_smoke_rejected(tmp_path):
b = _fake_bin(tmp_path)
app = _app(tmp_path)
(app / "scripts" / "admin_smoke.py").unlink()
r = _run(tmp_path, app, b)
assert r.returncode == 1
assert "admin_smoke.py" in r.stderr