108 lines
5.1 KiB
Python
108 lines
5.1 KiB
Python
#!/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()
|