From d3c7ceb0a099d563f074f993bcb926676760625a Mon Sep 17 00:00:00 2001 From: buryan-agent Date: Wed, 21 Oct 2026 15:07:34 +0300 Subject: [PATCH] =?UTF-8?q?[S-03]=20Prometheus:=20oauth2-proxy=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B4=D0=BD=D1=8F=D1=82=20=D0=B2=20CT134,=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=B9=D0=B4=D0=B5=D1=80=20Authentik=20=D1=81?= =?UTF-8?q?=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/STATUS.md | 2 +- ops/sso/prometheus_sso.py | 107 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 ops/sso/prometheus_sso.py diff --git a/ops/STATUS.md b/ops/STATUS.md index 4d209d3..78f7448 100644 --- a/ops/STATUS.md +++ b/ops/STATUS.md @@ -39,7 +39,7 @@ |---|---|---|---| | S-01 | SSO: Home Assistant | ⏳ | нужен компонент auth_oidc + провайдер; HA доступен по админ-паролю | | S-02 | SSO: Gitea | ✅ | вход через Authentik работает: кнопка на /user/login, провайдер gitea, редирект 302 | -| S-03 | SSO: Prometheus | ⏳ | Prometheus на :9090 внутри CT134, публичного домена нет; нужен oauth2-proxy + домен | +| S-03 | SSO: Prometheus | 🔄 | oauth2-proxy в CT134 :9113 работает (/ping 200), провайдер prometheus создан; осталось nginx+сертификат | | S-04 | Mosquitto — исключение | ✅ | `ops/adr/ADR-006-mosquitto-no-sso.md` | | S-05 | Мониторинг сервисов | ✅ | Kuma: 60 активных; добавлены Portainer, Seerr, Paperless, Immich | | S-06 | Ссылка на статус в карточках | ✅ | `ops/services/cards/` | diff --git a/ops/sso/prometheus_sso.py b/ops/sso/prometheus_sso.py new file mode 100644 index 0000000..a187702 --- /dev/null +++ b/ops/sso/prometheus_sso.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Корректно создаёт провайдер Prometheus и запускает oauth2-proxy.""" +import json +import subprocess +import urllib.error +import urllib.request + +API = "http://192.168.1.114:9000/api/v3" +TOKEN = open("/root/.authentik-api-token", encoding="utf-8").read().strip() +REDIRECT = "https://prometheus.buryans.ru/oauth2/callback" + + +def call(method, path, body=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(API + path, data=data, method=method, + headers={"Authorization": "Bearer " + TOKEN, + "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read() + return r.status, (json.loads(raw) if raw else {}) + except urllib.error.HTTPError as e: + return e.code, e.read()[:400].decode("utf-8", "replace") + + +def sh(cmd, timeout=180): + r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout or "").strip(), (r.stderr or "").strip() + + +def main(): + st, provs = call("GET", "/providers/oauth2/?page_size=100") + prov = next((p for p in provs.get("results", []) if p.get("name") == "Prometheus"), None) + if prov: + print("провайдер найден:", prov["client_id"]) + else: + st, flows = call("GET", "/flows/instances/?page_size=100") + by = {f["slug"]: f["pk"] for f in flows["results"]} + auth = by.get("default-provider-authorization-explicit-consent") + inval = by.get("default-provider-invalidation-flow") + st, keys = call("GET", "/crypto/certificatekeypairs/?page_size=50") + key = keys["results"][0]["pk"] if keys.get("results") else None + pks = [] + for q in ("/propertymappings/?managed__isnull=false&page_size=100", + "/propertymappings/?page_size=100"): + st, scopes = call("GET", q) + if st == 200 and isinstance(scopes, dict): + pks = [m["pk"] for m in scopes.get("results", []) + if m.get("scope_name") in ("openid", "email", "profile")] + if pks: + break + print("flows:", bool(auth), bool(inval), "| key:", bool(key), "| scopes:", len(pks)) + st, prov = call("POST", "/providers/oauth2/", { + "name": "Prometheus", "authorization_flow": auth, + "invalidation_flow": inval, "client_type": "confidential", + "redirect_uris": [{"matching_mode": "strict", "url": REDIRECT}], + "property_mappings": pks, "signing_key": key}) + if st not in (200, 201): + print("ошибка провайдера:", st, prov) + return + print("провайдер создан:", prov["client_id"]) + st, app = call("POST", "/core/applications/", { + "name": "Prometheus", "slug": "prometheus", + "provider": prov["pk"], "meta_launch_url": "https://prometheus.buryans.ru"}) + print("приложение:", st, app.get("slug") if isinstance(app, dict) else app) + + cfg = {"client_id": prov["client_id"], "client_secret": prov["client_secret"]} + json.dump(cfg, open("/root/.prometheus-oauth.json", "w")) + print("client_id:", cfg["client_id"]) + + sh("pct exec 134 -- docker rm -f oauth2-proxy-prometheus 2>/dev/null") + cookie = sh("openssl rand -hex 16")[1] + args = [ + "docker", "run", "-d", "--name", "oauth2-proxy-prometheus", + "--restart", "unless-stopped", "-p", "9113:4180", + "--add-host", "auth.buryans.ru:192.168.1.114", + "-e", f"OAUTH2_PROXY_CLIENT_ID={cfg['client_id']}", + "-e", f"OAUTH2_PROXY_CLIENT_SECRET={cfg['client_secret']}", + "-e", "OAUTH2_PROXY_PROVIDER=oidc", + "-e", "OAUTH2_PROXY_OIDC_ISSUER_URL=http://192.168.1.114:9000/application/o/prometheus/", + "-e", f"OAUTH2_PROXY_REDIRECT_URL={REDIRECT}", + "-e", "OAUTH2_PROXY_EMAIL_DOMAINS=*", + "-e", "OAUTH2_PROXY_UPSTREAMS=static://200", + "-e", "OAUTH2_PROXY_HTTP_ADDRESS=0.0.0.0:4180", + "-e", "OAUTH2_PROXY_SKIP_PROVIDER_BUTTON=true", + "-e", "OAUTH2_PROXY_SET_XAUTHREQUEST=true", + "-e", "OAUTH2_PROXY_COOKIE_SECURE=true", + "-e", f"OAUTH2_PROXY_COOKIE_SECRET={cookie}", + "-e", "OAUTH2_PROXY_INSECURE_OIDC_ALLOW_UNVERIFIED_EMAIL=true", + "-e", "OAUTH2_PROXY_SSL_INSECURE_SKIP_VERIFY=true", + "quay.io/oauth2-proxy/oauth2-proxy:latest", + ] + flat = " ".join(f"'{a}'" if "*" in a else a for a in args) + rc, out, err = sh(f"pct exec 134 -- {flat}") + print("run:", rc, (err or out)[:160]) + sh("sleep 6") + rc, out, _ = sh("pct exec 134 -- docker ps -a --filter name=oauth2-proxy-prometheus " + "--format '{{.Status}}'") + print("статус:", out) + rc, out, _ = sh("curl -s -o /dev/null -w '%{http_code}' --max-time 8 http://192.168.1.134:9113/ping") + print("/ping:", out) + rc, out, _ = sh("pct exec 134 -- docker logs --tail 4 oauth2-proxy-prometheus 2>&1") + print("лог:", out[:300]) + + +if __name__ == "__main__": + main()