179 lines
6.9 KiB
Python
179 lines
6.9 KiB
Python
"""Official ZITADEL API provisioning for ONE disposable, isolated Gitea run.
|
|
|
|
Read-only IAM_OWNER PAT from the ephemeral ZITADEL bootstrap volume.
|
|
Only output state is a 0600 JSON fixture on a distinct CI-owned Docker volume.
|
|
NEVER log PAT, client secrets, passwords, tokens, API JSON/error bodies.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
import sys
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
|
|
|
|
OWNER_PAT = Path("/zitadel/bootstrap/oidc-ci-owner.pat")
|
|
FIXTURE = Path("/ci/secret/oidc.json")
|
|
ISSUER = "http://localhost:8080"
|
|
ORIGIN = "http://127.0.0.1:8080"
|
|
TIMEOUT = 20
|
|
CLIENT_ID_KEYS = ("clientId",)
|
|
OPENER = build_opener(ProxyHandler({}))
|
|
|
|
|
|
class DenyRedirect(HTTPRedirectHandler):
|
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
raise RuntimeError("Unexpected redirect while provisioning local ZITADEL")
|
|
|
|
|
|
OPENER.add_handler(DenyRedirect())
|
|
|
|
|
|
def request(method: str, path: str, token: str | None = None, payload: dict | None = None) -> dict:
|
|
if not path.startswith("/") or path.startswith("//") or "://" in path or "?" in path:
|
|
raise RuntimeError("Unsafe provisioning endpoint")
|
|
body = None if payload is None else json.dumps(payload, separators=(",", ":")).encode()
|
|
headers = {"Host": "localhost:8080", "Accept": "application/json"}
|
|
if body is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
try:
|
|
with OPENER.open(Request(ORIGIN + path, data=body, headers=headers, method=method), timeout=TIMEOUT) as reply:
|
|
if reply.status != 200:
|
|
raise RuntimeError(f"Provisioning endpoint returned HTTP {reply.status}")
|
|
data = reply.read(1_000_001)
|
|
if len(data) > 1_000_000:
|
|
raise RuntimeError("Oversized provisioning API response")
|
|
except HTTPError as exc:
|
|
# No error response payload (may include secrets, login names or details).
|
|
raise RuntimeError(f"Official ZITADEL API {method} {path} returned HTTP {exc.code}") from None
|
|
except URLError as exc:
|
|
raise RuntimeError(f"ZITADEL API unavailable for {method} {path}") from None
|
|
if not data:
|
|
return {}
|
|
result = json.loads(data)
|
|
if not isinstance(result, dict):
|
|
raise RuntimeError("Invalid API response shape")
|
|
return result
|
|
|
|
|
|
def wait_until_ready() -> None:
|
|
deadline = time.monotonic() + 70
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
request("GET", "/debug/ready")
|
|
return
|
|
except RuntimeError:
|
|
time.sleep(2)
|
|
raise RuntimeError("Disposable localhost issuer port forwarding was not ready")
|
|
|
|
|
|
def required_string(data: dict, name: str) -> str:
|
|
value = data.get(name)
|
|
if not isinstance(value, str) or not value or len(value) > 4096:
|
|
raise RuntimeError(f"ZITADEL response missing required {name}")
|
|
return value
|
|
|
|
|
|
def main() -> None:
|
|
run = os.environ.get("OIDC_CI_RUN_ID", "")
|
|
if not run.isdecimal() or len(run) > 18:
|
|
raise RuntimeError("Invalid disposable Gitea run ID")
|
|
if not FIXTURE.parent.is_dir() or FIXTURE.exists():
|
|
raise RuntimeError("Secret fixture volume missing or already used")
|
|
wait_until_ready()
|
|
print("ZITPLANE_OIDC_LOCAL_ORIGIN_READY_PASS", flush=True)
|
|
discovery = request("GET", "/.well-known/openid-configuration")
|
|
if discovery.get("issuer") != ISSUER:
|
|
raise RuntimeError("Disposable OIDC issuer mismatch")
|
|
for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
|
|
if not isinstance(discovery.get(field), str) or not discovery[field].startswith(ISSUER + "/"):
|
|
raise RuntimeError(f"Invalid discovery {field} origin")
|
|
print("ZITPLANE_OIDC_ISSUER_DISCOVERY_PASS", flush=True)
|
|
|
|
if not OWNER_PAT.is_file():
|
|
raise RuntimeError("Disposable first-instance IAM_OWNER PAT was not issued")
|
|
pat = OWNER_PAT.read_text(encoding="utf-8").strip()
|
|
if len(pat) < 20:
|
|
raise RuntimeError("Invalid disposable IAM_OWNER PAT length")
|
|
|
|
project = request(
|
|
"POST", "/management/v1/projects", pat,
|
|
{"name": f"zitplane-oidc-ci-{run}"},
|
|
)
|
|
project_id = required_string(project, "id")
|
|
print("ZITPLANE_OIDC_PROJECT_CREATED_PASS", flush=True)
|
|
|
|
app = request(
|
|
"POST", f"/management/v1/projects/{project_id}/apps/oidc", pat,
|
|
{
|
|
"name": "ZitPlane_Disposable_Account_OIDC",
|
|
"redirectUris": ["http://localhost:3000/api/auth/callback/zitadel"],
|
|
"postLogoutRedirectUris": ["http://localhost:3000"],
|
|
"responseTypes": ["OIDC_RESPONSE_TYPE_CODE"],
|
|
"grantTypes": ["OIDC_GRANT_TYPE_AUTHORIZATION_CODE"],
|
|
"appType": "OIDC_APP_TYPE_WEB",
|
|
"authMethodType": "OIDC_AUTH_METHOD_TYPE_BASIC",
|
|
"version": "OIDC_VERSION_1_0",
|
|
"devMode": True,
|
|
},
|
|
)
|
|
client_id = required_string(app, "clientId")
|
|
client_secret = required_string(app, "clientSecret")
|
|
required_string(app, "appId")
|
|
print("ZITPLANE_OIDC_REAL_CLIENT_CREATED_PASS", flush=True)
|
|
|
|
# Invalid TLD and verified email ensure no delivery to any real account.
|
|
login_name = f"oidc-ci-{run}@example.invalid"
|
|
password = "Zp!7" + secrets.token_urlsafe(38)
|
|
human = request(
|
|
"POST", "/v2/users/human", pat,
|
|
{
|
|
"username": login_name,
|
|
"profile": {
|
|
"givenName": "Disposable",
|
|
"familyName": "Acceptance",
|
|
"preferredLanguage": "en",
|
|
},
|
|
"email": {"email": login_name, "isVerified": True},
|
|
"password": {"password": password, "changeRequired": False},
|
|
},
|
|
)
|
|
user_id = required_string(human, "userId")
|
|
print("ZITPLANE_OIDC_REAL_TEST_HUMAN_CREATED_PASS", flush=True)
|
|
|
|
# Write secrets only inside an explicit CI-created, non-reused Docker volume;
|
|
# browser has this volume read-only, never the owner PAT. No stdout JSON.
|
|
fixture = {
|
|
"issuer": ISSUER,
|
|
"clientId": client_id,
|
|
"clientSecret": client_secret,
|
|
"authSecret": secrets.token_urlsafe(48),
|
|
"userId": user_id,
|
|
"loginName": login_name,
|
|
"password": password,
|
|
}
|
|
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
|
|
fd = os.open(FIXTURE, flags, 0o600)
|
|
try:
|
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
json.dump(fixture, handle)
|
|
handle.write("\n")
|
|
except BaseException:
|
|
FIXTURE.unlink(missing_ok=True)
|
|
raise
|
|
print("ZITPLANE_OIDC_TEST_CREDENTIALS_ISOLATED_PASS", flush=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Exception as exc:
|
|
# Only our intentionally redacted statuses, not raw traceback/request.
|
|
print(f"ZITPLANE_OIDC_PROVISION_BLOCKED: {str(exc)[:210]}", file=sys.stderr)
|
|
sys.exit(1)
|