80 lines
2.8 KiB
Python
80 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
import secrets
|
|
from typing import Any
|
|
|
|
from ..settings import settings
|
|
from ..utils.logging import get_logger
|
|
from .keycloak_admin import keycloak_admin
|
|
from .vault import vault
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
def _oauth_client_payload(client_id: str, base_url: str) -> dict[str, Any]:
|
|
return {
|
|
"clientId": client_id,
|
|
"enabled": True,
|
|
"protocol": "openid-connect",
|
|
"publicClient": False,
|
|
"standardFlowEnabled": True,
|
|
"implicitFlowEnabled": False,
|
|
"directAccessGrantsEnabled": False,
|
|
"serviceAccountsEnabled": False,
|
|
"redirectUris": [f"{base_url}/oauth2/callback"],
|
|
"webOrigins": [base_url],
|
|
"rootUrl": base_url,
|
|
"baseUrl": "/",
|
|
}
|
|
|
|
|
|
def _valid_cookie_secret(value: Any) -> str:
|
|
if not isinstance(value, str):
|
|
return ""
|
|
stripped = value.strip()
|
|
return stripped if len(stripped) in {16, 24, 32} else ""
|
|
|
|
|
|
class OAuth2ProxyService:
|
|
"""Ensure Keycloak and Vault state for oauth2-proxy frontends."""
|
|
|
|
def ensure_wolf(self) -> dict[str, Any]:
|
|
if not keycloak_admin.ready():
|
|
return {"status": "error", "detail": "keycloak admin client not configured"}
|
|
|
|
client_id = settings.wolf_oidc_client_id
|
|
base_url = settings.wolf_oidc_base_url
|
|
client = keycloak_admin.find_client(client_id)
|
|
payload = _oauth_client_payload(client_id, base_url)
|
|
if not client:
|
|
keycloak_admin.create_client(payload)
|
|
client = keycloak_admin.find_client(client_id)
|
|
if not client:
|
|
raise RuntimeError(f"keycloak client {client_id} not found")
|
|
|
|
client_uuid = str(client.get("id") or "")
|
|
if not client_uuid:
|
|
raise RuntimeError("keycloak client id missing")
|
|
|
|
keycloak_admin.update_client(client_uuid, payload)
|
|
scope_id = keycloak_admin.find_client_scope_id("groups")
|
|
if scope_id:
|
|
keycloak_admin.attach_optional_client_scope(client_uuid, scope_id)
|
|
|
|
client_secret = keycloak_admin.get_client_secret(client_uuid)
|
|
existing = vault.read_kv_secret(settings.wolf_oidc_vault_path) or {}
|
|
cookie_secret = _valid_cookie_secret(existing.get("cookie_secret")) or secrets.token_hex(16)
|
|
vault.write_kv_secret(
|
|
settings.wolf_oidc_vault_path,
|
|
{"client_id": client_id, "client_secret": client_secret, "cookie_secret": cookie_secret},
|
|
)
|
|
logger.info("wolf oauth2 proxy secret ensured", extra={"event": "wolf_oidc_ensure", "client_id": client_id})
|
|
return {"status": "ok", "client_id": client_id, "base_url": base_url, "vault_path": settings.wolf_oidc_vault_path}
|
|
|
|
def ensure_sunshine(self) -> dict[str, Any]:
|
|
return self.ensure_wolf()
|
|
|
|
|
|
oauth2_proxy = OAuth2ProxyService()
|