Files

96 lines
3.5 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Проверка входа в Matrix: Synapse, SSO-редирект, authorize в Authentik.
ВАЖНО (исправлено 16.11.2026): проверки идут через ЛОКАЛЬНЫЕ адреса.
Раньше чекер ходил на https://matrix.buryans.ru изнутри хоста — публичный
домен изнутри упирается в DPI/hairpin NAT и даёт
«_ssl.c:1012: The handshake operation timed out», хотя сервис жив.
Теперь: Synapse — напрямую 192.168.1.155:8008, домены — через локальный
nginx с Host-заголовком (nginx на хосте терминирует TLS).
"""
import json
import subprocess
import sys
import urllib.request as u
HUB = "http://127.0.0.1:9120"
CID = "kEkzD2jN1Pgmg2wrCjzCXDuDcl4pD7p9yDbX81d3"
RED = "https://matrix.buryans.ru/_synapse/client/oidc/callback"
SYNAPSE = "http://192.168.1.155:8008"
NGINX = "https://127.0.0.1"
# (имя, тип, цель, путь, ожидаемые коды)
CHECKS = [
("synapse versions", "url", SYNAPSE, "/_matrix/client/versions", (200,)),
("sso redirect", "url", SYNAPSE,
"/_matrix/client/v3/login/sso/redirect/oidc-authentik?redirectUrl=https%3A%2F%2Felement.buryans.ru%2F",
(302,)),
("authentik authorize", "host", "authentik.buryans.ru",
"/application/o/authorize/?client_id=%s&response_type=code&scope=openid"
"&redirect_uri=%s&state=t" % (CID, RED), (200, 302)),
("element", "host", "element.buryans.ru", "/", (200, 302)),
]
class NoRedirect(u.HTTPRedirectHandler):
"""Редирект — ожидаемый результат, не идём по нему."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
OPENER = u.build_opener(NoRedirect)
def code_url(url, timeout=15):
req = u.Request(url, headers={"User-Agent": "hub-check/1"})
try:
with OPENER.open(req, timeout=timeout) as r:
return r.status
except u.HTTPError as e:
return e.code
except Exception as e:
return "ERR:" + str(e)[:40]
def code_host(host, path, timeout=12):
"""Через локальный nginx с Host-заголовком: TLS терминирует nginx."""
try:
r = subprocess.run(
["curl", "-s", "-k", "-o", "/dev/null", "-w", "%{http_code}",
"-m", str(timeout), "-H", "Host: " + host, NGINX + path],
capture_output=True, text=True, timeout=timeout + 5)
c = (r.stdout or "").strip()
return int(c) if c.isdigit() and c != "000" else "ERR:" + c
except Exception as e:
return "ERR:" + str(e)[:40]
def notify(message, priority="high"):
body = json.dumps({"title": "Matrix/SSO", "message": message,
"priority": priority}).encode()
req = u.Request(HUB + "/notify", data=body, headers={"Content-Type": "application/json"})
try:
with u.urlopen(req, timeout=10) as r:
return r.status
except Exception:
return 0
def main():
bad = []
for name, kind, target, path, ok in CHECKS:
c = code_url(target + path) if kind == "url" else code_host(target, path)
mark = "ok" if c in ok else "СБОЙ"
print("%-22s %s (%s)" % (name, c, mark))
if c not in ok:
bad.append("%s → %s" % (name, c))
if bad:
notify("🔴 Вход в Matrix сломан: " + "; ".join(bad), "high")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())