File size: 6,238 Bytes
842d5f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | """WebsiteBench Harbor foreground entrypoint for the frozen clone."""
from __future__ import annotations
import json
import os
import re
import smtplib
import urllib.error
import urllib.parse
import urllib.request
from email.message import EmailMessage
from http.cookies import SimpleCookie
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"
HARBOR_MAILBOX_HOSTS = frozenset(
{"127.0.0.1", "::1", "localhost", "mailbox-internal"}
)
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:
"""Acquire the trial-local, write-only mailbox identity."""
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 HARBOR_MAILBOX_HOSTS
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 HARBOR_MAILBOX_HOSTS
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()
DELIVERED_MAIL_IDS: set[int] = set()
import app as clone_module # noqa: E402
clone_app = clone_module.app
def _session_tokens(
scope: dict[str, object], response_headers: list[tuple[bytes, bytes]]
) -> set[str]:
tokens: set[str] = set()
raw_cookies = [
value.decode("latin-1")
for name, value in scope.get("headers", [])
if name.lower() == b"cookie"
]
raw_cookies.extend(
value.decode("latin-1")
for name, value in response_headers
if name.lower() == b"set-cookie"
)
for raw in raw_cookies:
parsed = SimpleCookie()
try:
parsed.load(raw)
except Exception:
continue
name = clone_module.AUTH_SESSION_COOKIE
if name in parsed and parsed[name].value:
tokens.add(parsed[name].value)
return tokens
def _deliver_harbor_mail(session_tokens: set[str]) -> 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
response_headers: list[tuple[bytes, bytes]] = []
async def deliver_before_final_body(message):
if message.get("type") == "http.response.start":
response_headers[:] = list(message.get("headers", []))
if (
message.get("type") == "http.response.body"
and not message.get("more_body", False)
):
_deliver_harbor_mail(_session_tokens(scope, response_headers))
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,
)
|