[SSO] Защита от повторения: check_sso_providers.py проверяет у всех 68 провайдеров grant_types, signing_key, property_mappings и redirect_uris, плюс https-issuer у oauth2-proxy. Задание Hermes ежедневно 07:05. Сейчас 0 проблем

This commit is contained in:
root committed 2026-11-10 15:53:51 +03:00
1 parent fbf0bf55ea
commit e609fa8b52
2 files changed
+166

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Проверка OAuth-провайдеров Authentik: ловит то, что ломало вход.
Проверяет у каждого провайдера четыре поля, из-за которых SSO молча не работает:
* grant_types содержит authorization_code
* signing_key назначен (иначе JWKS пуст и подпись не проверить)
* property_mappings не пуст (иначе в токене нет email)
* redirect_uris не пуст
Плюс отдельно: issuer у oauth2-proxy должен быть https (иначе прокси не тянет JWKS).
Запуск: python3 ops/scripts/check_sso_providers.py [--fix]
"""
import json
import subprocess
import sys
import urllib.request as u
TOK = open("/root/.authentik-api-token").read().strip()
API = "http://192.168.1.114:9000/api/v3"
HDR = {"Authorization": "Bearer " + TOK, "Content-Type": "application/json"}
DEFAULT_MAPS = ["b4789a71-b08e-49bf-8d59-00aa78bc8b76",
"3ecf71c7-0d37-436d-9b9d-0634f9abc28b",
"11eaf97b-55fd-457a-b91f-fff4cecffc4f"]
def api(path, method="GET", body=None):
data = json.dumps(body).encode() if body is not None else None
req = u.Request(API + path, data=data, method=method, headers=HDR)
with u.urlopen(req, timeout=25) as r:
raw = r.read()
return json.loads(raw) if raw else {}
def problems(p):
out = []
gt = p.get("grant_types") or []
if "authorization_code" not in gt:
out.append("нет authorization_code в grant_types")
if not p.get("signing_key"):
out.append("не назначен signing_key (JWKS пуст)")
if not (p.get("property_mappings") or []):
out.append("пустые property_mappings (нет email в токене)")
if not (p.get("redirect_uris") or []):
out.append("нет redirect_uris")
return out
def main():
fix = "--fix" in sys.argv
d = api("/providers/oauth2/?page_size=100")
items = d.get("results") or []
bad = []
for p in items:
pr = problems(p)
if pr:
bad.append((p, pr))
print("провайдеров:", len(items), "| с проблемами:", len(bad))
for p, pr in bad:
print(" ⛔ %-34s %s" % ((p.get("name") or "")[:34], "; ".join(pr)))
if fix and bad:
print("\nисправляю:")
for p, pr in bad:
body = {}
gt = p.get("grant_types") or []
if "authorization_code" not in gt:
body["grant_types"] = ["authorization_code", "refresh_token"]
if not p.get("property_mappings"):
body["property_mappings"] = DEFAULT_MAPS
if not p.get("signing_key"):
body["signing_key"] = "af0928d2-4741-4b9a-b88b-5f7015304923"
if body:
try:
api("/providers/oauth2/%s/" % p["pk"], "PATCH", body)
print(" ✓ %s" % (p.get("name") or "")[:40])
except Exception as e:
print(" ✗ %s: %s" % ((p.get("name") or "")[:30], str(e)[:60]))
# проверка issuer у oauth2-proxy
out = subprocess.run(
"pct exec 109 -- docker inspect oauth2-proxy-vaultwarden "
"--format '{{range .Config.Env}}{{println .}}{{end}}'",
shell=True, capture_output=True, text=True, timeout=60).stdout
issuer = ""
for line in out.splitlines():
if line.startswith("OAUTH2_PROXY_OIDC_ISSUER_URL="):
issuer = line.split("=", 1)[1].strip()
if issuer and not issuer.startswith("https://"):
print(" ⛔ oauth2-proxy issuer не https: %s (прокси не тянет JWKS)" % issuer)
elif issuer:
print(" ✓ oauth2-proxy issuer: %s" % issuer)
return 1 if bad else 0
if __name__ == "__main__":
raise SystemExit(main())