"""KAB access tokens for unattended runs: the `kab-automation` client of realm `kab`, by client credentials. The client and its secret are provisioned by the Stellwerk orchestrator (crucible-platform-deploy, `kab-cluster/dev` component 85; module `kab-identity`). The secret is in Key Vault `crucible-kab-dev-kv` as `kab-automation-client-secret` and reaches the runner as the environment variable KAB_CLIENT_SECRET (a mounted Secret on the cluster). Tokens carry the fixed email claim KAB knows the automation user by. The secret and every token stay in memory: never written to a file, the ledger or a log, and never printed. """ from __future__ import annotations import json import os import time import urllib.error import urllib.parse import urllib.request from typing import Callable DEFAULT_TOKEN_URL = "https://id.kab-dev.kyndemo.live/realms/kab/protocol/openid-connect/token" DEFAULT_CLIENT_ID = "kab-automation" REFRESH_MARGIN_S = 60 class AuthError(RuntimeError): pass def _post_form(url: str, form: dict, timeout: int = 30) -> dict: body = urllib.parse.urlencode(form).encode() request = urllib.request.Request(url, data=body, headers={"Content-Type": "application/x-www-form-urlencoded"}) try: with urllib.request.urlopen(request, timeout=timeout) as response: return json.load(response) except urllib.error.HTTPError as error: try: reason = json.loads(error.read() or b"{}").get("error_description") or "no reason given" except ValueError: reason = "no reason given" raise AuthError(f"token request refused: HTTP {error.code}: {reason}") from None except urllib.error.URLError as error: raise AuthError(f"token endpoint unreachable: {error.reason}") from None class ClientCredentials: """A token source that renews itself a minute before the token expires.""" def __init__(self, client_id: str, secret: str, token_url: str = DEFAULT_TOKEN_URL, post: Callable[[str, dict], dict] = _post_form, clock: Callable[[], float] = time.time) -> None: if not secret: raise AuthError("no client secret: set KAB_CLIENT_SECRET (the kab-automation client's secret)") self.client_id = client_id self._secret = secret self.token_url = token_url self._post = post self._clock = clock self._token: str | None = None self._expires_at = 0.0 @classmethod def from_env(cls) -> "ClientCredentials": return cls(os.getenv("KAB_CLIENT_ID", DEFAULT_CLIENT_ID), os.getenv("KAB_CLIENT_SECRET", ""), os.getenv("KAB_TOKEN_URL", DEFAULT_TOKEN_URL)) def __repr__(self) -> str: # never show the secret or the token return f"ClientCredentials(client_id={self.client_id!r}, token_url={self.token_url!r})" def token(self, force: bool = False) -> str: if force or self._token is None or self._clock() >= self._expires_at - REFRESH_MARGIN_S: reply = self._post(self.token_url, {"grant_type": "client_credentials", "client_id": self.client_id, "client_secret": self._secret}) if not reply.get("access_token"): raise AuthError("token reply has no access_token") self._token = reply["access_token"] self._expires_at = self._clock() + float(reply.get("expires_in") or 300) return self._token def expires_in(self) -> int: return max(0, int(self._expires_at - self._clock()))