#!/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 outside_compose(): """oauth2-proxy без compose = конфигурация не сохранена, потеряется при пересоздании.""" out = [] try: cts = subprocess.run("pct list | awk 'NR>1{print $1}'", shell=True, capture_output=True, text=True, timeout=30).stdout.split() except Exception: return out for ct in cts: names = subprocess.run("pct exec %s -- docker ps --format '{{.Names}}'" % ct, shell=True, capture_output=True, text=True, timeout=30).stdout.split() for n in names: if not n.startswith("oauth2-proxy"): continue proj = subprocess.run( "pct exec %s -- docker inspect %s --format " "'{{index .Config.Labels \"com.docker.compose.project\"}}'" % (ct, n), shell=True, capture_output=True, text=True, timeout=30).stdout.strip() if not proj or proj == "": out.append("CT%s %s" % (ct, n)) 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) lost = outside_compose() if lost: print(" ⛔ oauth2-proxy вне compose (конфиг потеряется): %d" % len(lost)) for x in lost[:10]: print(" %s" % x) else: print(" ✓ все oauth2-proxy под compose") return 1 if (bad or lost) else 0 if __name__ == "__main__": raise SystemExit(main())