import json import os import urllib.error import urllib.parse import urllib.request AUTH0_TOKEN_URL = "https://tidb-soc2.us.auth0.com/oauth/token" AUTH0_AUDIENCE = "https://tidb-soc2.us.auth0.com/api/v2/" VENDOR = "aws" TENANT_ID = "62" PROJECT_ID = "2" APPLICATION_ID = "cp9-platform-readiness" def request( method, url, *, body=None, json_body=None, headers=None, bearer=None, expected=(200,), ): headers = dict(headers or {}) if json_body is not None: if body is not None: raise ValueError("request body cannot be both raw and JSON") body = json.dumps(json_body).encode() headers["content-type"] = "application/json" if bearer is not None: headers["authorization"] = f"Bearer {bearer}" req = urllib.request.Request(url, data=body, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=20) as response: payload = response.read() status = response.status except urllib.error.HTTPError as exc: payload = exc.read() status = exc.code if status not in expected: detail = payload.decode(errors="replace")[:500] raise RuntimeError(f"{method} {url} returned HTTP {status}: {detail}") return status, payload def request_json(method, url, **kwargs): status, payload = request(method, url, **kwargs) try: return status, json.loads(payload) except json.JSONDecodeError as exc: raise RuntimeError(f"{method} {url} returned invalid JSON") from exc def auth0_token(): status, response = request_json( "POST", AUTH0_TOKEN_URL, json_body={ "client_id": os.environ["CP9_AUTH0_CLIENT_ID"], "client_secret": os.environ["CP9_AUTH0_CLIENT_SECRET"], "audience": AUTH0_AUDIENCE, "grant_type": "client_credentials", }, ) token = response.get("access_token") if not isinstance(token, str) or not token: raise RuntimeError("Auth0 token response did not contain an access token") return status, token def cluster_identity(region, biz_type): return { "vendor": VENDOR, "region": region, "bizType": biz_type, "tenantID": TENANT_ID, "projectID": PROJECT_ID, "applicationID": APPLICATION_ID, } def cluster_query(region, biz_type): return urllib.parse.urlencode(cluster_identity(region, biz_type))