"""WebsiteBench Harbor foreground entrypoint for the frozen clone.""" from __future__ import annotations import json import os import re import secrets import smtplib import urllib.error import urllib.parse import urllib.request from email.message import EmailMessage from pathlib import Path import uvicorn ROOT = Path(__file__).resolve().parent SITE_ROOT = ROOT.parent RUNTIME = json.loads((SITE_ROOT / "backend" / "runtime.json").read_text(encoding="utf-8")) SITE_ID = str(RUNTIME["site"]["id"]) DATA_DIR = Path(os.environ["DATA_DIR"]) if not DATA_DIR.is_absolute(): raise RuntimeError("DATA_DIR must be absolute") DATA_DIR = DATA_DIR.resolve() DATA_DIR.mkdir(parents=True, exist_ok=True) os.environ["WEBSITEBENCH_DATA_DIR"] = str(DATA_DIR) os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(SITE_ROOT / "backend" / "runtime.json") os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(DATA_DIR / RUNTIME["database"]["filename"]) if os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip(): os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor" os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = "local-sandbox" class _NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, fp, code, msg, headers, newurl): del request, fp, code, msg, headers, newurl return None def _harbor_mailbox_identity() -> dict[str, object] | None: bootstrap_url = os.environ.get("WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL", "").strip() bootstrap_token = os.environ.get( "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN", "" ).strip() if not bootstrap_url and not bootstrap_token: return None parsed = urllib.parse.urlsplit(bootstrap_url) if ( parsed.scheme != "http" or parsed.hostname not in { "127.0.0.1", "::1", "localhost", "mailbox-internal", } or parsed.username is not None or parsed.password is not None or len(bootstrap_token) < 32 ): raise RuntimeError("Harbor mailbox bootstrap configuration is invalid") request = urllib.request.Request( bootstrap_url, headers={ "Accept": "application/json", "Authorization": f"Bearer {bootstrap_token}", }, method="GET", ) try: with urllib.request.build_opener(_NoRedirect).open( request, timeout=10 ) as response: raw = response.read(64 * 1024 + 1) except (OSError, urllib.error.URLError) as exc: raise RuntimeError("Harbor mailbox bootstrap is unavailable") from exc if len(raw) > 64 * 1024: raise RuntimeError("Harbor mailbox bootstrap response is too large") try: identity = json.loads(raw.decode("utf-8")) namespace = str(identity["namespace"]) capability = str(identity["capability"]) smtp_host = str(identity["smtp_host"]) smtp_port = int(identity["smtp_port"]) except (KeyError, TypeError, ValueError, UnicodeError, json.JSONDecodeError) as exc: raise RuntimeError("Harbor mailbox bootstrap response is invalid") from exc if ( re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", namespace) is None or len(namespace) > 128 or len(capability) < 32 or smtp_host not in {"127.0.0.1", "::1", "localhost", "mailbox-internal"} or not 1 <= smtp_port <= 65535 ): raise RuntimeError("Harbor mailbox identity is invalid") return { "namespace": namespace, "capability": capability, "smtp_host": smtp_host, "smtp_port": smtp_port, } MAILBOX_IDENTITY = _harbor_mailbox_identity() MAIL_WORKER_TOKEN = secrets.token_hex(32) if MAILBOX_IDENTITY is not None else None if MAIL_WORKER_TOKEN is not None: os.environ["ETSY_HARBOR_MAIL_WORKER_TOKEN"] = MAIL_WORKER_TOKEN import app as clone_module # noqa: E402 clone_app = clone_module.app def _deliver_harbor_mail() -> None: """Compatibility hook; the auth store delivers synchronously to Mailpit.""" return None HEALTH_BODY = b'{"status":"ok"}' # /healthz is the contract (ADR-0010); the private path stays mounted # so bundles frozen before the migration keep answering. HEALTH_PATHS = ("/healthz", "/__websitebench/health") async def application(scope, receive, send): if scope.get("type") == "http" and scope.get("path") in HEALTH_PATHS: await send({ "type": "http.response.start", "status": 200, "headers": [ (b"content-type", b"application/json"), (b"content-length", str(len(HEALTH_BODY)).encode("ascii")), (b"cache-control", b"no-store"), ], }) await send({"type": "http.response.body", "body": HEALTH_BODY}) return async def deliver_before_final_body(message): if ( message.get("type") == "http.response.body" and not message.get("more_body", False) ): _deliver_harbor_mail() await send(message) await clone_app(scope, receive, deliver_before_final_body) if __name__ == "__main__": uvicorn.run( application, host=os.environ["HOST"], port=int(os.environ["PORT"]), access_log=False, timeout_graceful_shutdown=2, )