feat(админка): independent admin_smoke и cron-строка без токена
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Дешёвая independent-проба админки: без токена, без модели, раз в 15 минут.
|
||||
|
||||
Зачем: `/health` и `journey_canary` не смотрят на админку. Битый CSP, упавший
|
||||
`app.js` или 500 на странице `/admin` дают зелёный `/health` и зелёную
|
||||
канарейку, которая ходит только по чату. Эта проба смотрит ровно то, что
|
||||
открывает владелец, и пишет след в state-файл, который читает приёмка.
|
||||
|
||||
Проверки:
|
||||
1. `/api/version` — 200 и версия;
|
||||
2. `/health` — 200;
|
||||
3. `/admin` (с редиректами) — 200, HTML, оболочка legacy или v2;
|
||||
4. CSP: для v2 — без `unsafe-inline` в `script-src`; для legacy — можно.
|
||||
|
||||
Не заменяет `journey_canary` (тот ходит по чату и почте), а закрывает слепое
|
||||
пятно админки. Запуск:
|
||||
python3 scripts/admin_smoke.py --base-url https://infosmeta.ru
|
||||
python3 scripts/admin_smoke.py --state /data_safe/backups/smeta-web/admin_smoke.state
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_BASE = os.environ.get("ADMIN_SMOKE_BASE", "http://127.0.0.1:8101")
|
||||
DEFAULT_STATE = os.environ.get("ADMIN_SMOKE_STATE", "")
|
||||
TIMEOUT = float(os.environ.get("ADMIN_SMOKE_TIMEOUT", "15"))
|
||||
|
||||
|
||||
def _get(url: str, retries: int = 3):
|
||||
"""Три попытки: прокси/сеть рвут TLS и без падения сервиса."""
|
||||
last: Exception | None = None
|
||||
for n in range(retries):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "smeta-admin-smoke/1"})
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
body = r.read(2 * 1024 * 1024).decode("utf-8", "replace")
|
||||
return r.status, r.headers, body
|
||||
except Exception as e: # noqa: BLE001
|
||||
last = e
|
||||
if n + 1 < retries:
|
||||
time.sleep(1 + n)
|
||||
raise last # type: ignore[misc]
|
||||
|
||||
|
||||
def _csp_script_policy(csp: str) -> tuple[bool, bool]:
|
||||
"""(есть ли политика скриптов, разрешён ли inline в эффективной политике).
|
||||
|
||||
`script-src-elem` управляет <script>, `script-src-attr` — inline-обработчиками;
|
||||
каждая падает назад: elem → script-src → default-src, attr → script-src → default-src.
|
||||
Порядок директив в заголовке не важен. `unsafe-inline` в эффективной ветке — не строго.
|
||||
"""
|
||||
directives: dict[str, str] = {}
|
||||
for part in (csp or "").split(";"):
|
||||
bits = part.strip().split()
|
||||
if bits:
|
||||
directives.setdefault(bits[0].lower(), " ".join(bits[1:]).lower())
|
||||
|
||||
def pick(*names: str) -> str:
|
||||
for n in names:
|
||||
if n in directives:
|
||||
return directives[n]
|
||||
return ""
|
||||
|
||||
def allows_inline(value: str) -> bool:
|
||||
# CSP2+: unsafe-inline игнорируется, если есть nonce-… или sha256/384/512-…
|
||||
if "unsafe-inline" not in value:
|
||||
return False
|
||||
tokens = value.replace("'", "").split()
|
||||
return not any(tok.startswith(("nonce-", "sha256-", "sha384-", "sha512-"))
|
||||
for tok in tokens)
|
||||
|
||||
elem = pick("script-src-elem", "script-src", "default-src")
|
||||
attr = pick("script-src-attr", "script-src", "default-src")
|
||||
has = bool(elem or attr)
|
||||
unsafe = any(allows_inline(x) for x in (elem, attr) if x)
|
||||
return has, unsafe
|
||||
|
||||
|
||||
class _ShellParser(HTMLParser):
|
||||
"""v2 — реальный <div id="app"> или <script src="/static/admin2/…">; legacy — nav.sidebar."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.v2 = False
|
||||
self.legacy = False
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
a = {k: (v or "") for k, v in attrs}
|
||||
if tag == "div" and a.get("id") == "app":
|
||||
self.v2 = True
|
||||
if tag == "script" and "/static/admin2/" in a.get("src", ""):
|
||||
self.v2 = True
|
||||
if tag == "nav" and "sidebar" in a.get("class", ""):
|
||||
self.legacy = True
|
||||
|
||||
|
||||
def _shell(body: str) -> str:
|
||||
p = _ShellParser()
|
||||
try:
|
||||
p.feed(body)
|
||||
except Exception: # noqa: BLE001
|
||||
return "unknown"
|
||||
if p.v2:
|
||||
return "v2"
|
||||
if p.legacy:
|
||||
return "legacy"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def check(base_url: str) -> dict:
|
||||
base = base_url.rstrip("/")
|
||||
result: dict = {"ts": time.time(), "base_url": base, "ok": False, "checks": {},
|
||||
"version": None, "shell": None, "csp_unsafe_inline": None, "csp_present": None, "csp_has_script_policy": None,
|
||||
"error": None, "errors": []}
|
||||
try:
|
||||
code, _, body = _get(base + "/api/version")
|
||||
data = json.loads(body)
|
||||
result["checks"]["version"] = (code == 200 and bool(data.get("version")))
|
||||
result["version"] = data.get("version")
|
||||
except Exception as e: # noqa: BLE001
|
||||
result["checks"]["version"] = False
|
||||
result["errors"].append(f"version: {type(e).__name__}: {e}")
|
||||
|
||||
try:
|
||||
code, _, _ = _get(base + "/health")
|
||||
result["checks"]["health"] = (code == 200)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result["checks"]["health"] = False
|
||||
result["errors"].append(f"health: {type(e).__name__}: {e}")
|
||||
|
||||
try:
|
||||
code, headers, body = _get(base + "/admin")
|
||||
shell = _shell(body)
|
||||
result["shell"] = shell
|
||||
result["checks"]["shell"] = (shell != "unknown")
|
||||
result["checks"]["admin"] = (code == 200 and "Админ-панель" in body and shell != "unknown")
|
||||
csp_list = headers.get_all("Content-Security-Policy") or [] # HTTPMessage регистронезависим
|
||||
policies = [_csp_script_policy(c) for c in csp_list]
|
||||
result["csp_present"] = bool(policies)
|
||||
result["csp_has_script_policy"] = bool(policies) and all(h for h, _ in policies)
|
||||
# несколько политик применяются совместно: inline разрешён, только если разрешён КАЖДОЙ
|
||||
result["csp_unsafe_inline"] = bool(policies) and all(u for _, u in policies)
|
||||
# legacy пока живёт без/с unsafe-inline; v2 обязан иметь политику скриптов и быть строгим.
|
||||
result["checks"]["csp"] = ((result["csp_present"] and result["csp_has_script_policy"]
|
||||
and not result["csp_unsafe_inline"]) if shell == "v2"
|
||||
else True if shell == "legacy" else False)
|
||||
except Exception as e: # noqa: BLE001
|
||||
result["checks"]["admin"] = False
|
||||
result["checks"]["csp"] = False
|
||||
result["errors"].append(f"admin: {type(e).__name__}: {e}")
|
||||
|
||||
result["ok"] = all(result["checks"].values())
|
||||
result["error"] = "; ".join(result["errors"]) or None
|
||||
return result
|
||||
|
||||
|
||||
def write_state(path: str, result: dict) -> str | None:
|
||||
"""Пишет state; возвращает текст ошибки, но не валит основной вывод."""
|
||||
if not path:
|
||||
return None
|
||||
p = Path(path)
|
||||
try:
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = p.with_name(p.name + f".{os.getpid()}.tmp")
|
||||
try:
|
||||
tmp.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
tmp.replace(p)
|
||||
finally:
|
||||
try:
|
||||
tmp.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
except Exception as e: # noqa: BLE001
|
||||
return f"{type(e).__name__}: {e}"
|
||||
return None
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(description="independent-проба админки без токена")
|
||||
ap.add_argument("--base-url", default=DEFAULT_BASE)
|
||||
ap.add_argument("--state", default=DEFAULT_STATE)
|
||||
ap.add_argument("--json", action="store_true")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
result = check(args.base_url)
|
||||
state_error = write_state(args.state, result)
|
||||
if state_error:
|
||||
result["state_error"] = state_error
|
||||
if args.json:
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
else:
|
||||
bad = [k for k, v in result["checks"].items() if not v]
|
||||
print(f"admin_smoke: {'ok' if result['ok'] else 'FAIL'} "
|
||||
f"version={result['version']} shell={result['shell']} "
|
||||
f"csp_unsafe_inline={result['csp_unsafe_inline']} "
|
||||
f"{('bad=' + ','.join(bad)) if bad else ''}"
|
||||
f"{(' error=' + result['error']) if result['error'] else ''}"
|
||||
f"{(' state_error=' + state_error) if state_error else ''}")
|
||||
return 0 if result["ok"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user