Download tasks/brooklinen/environment/reference/harbor_entry.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/brooklinen/environment/reference/harbor_entry.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/brooklinen/environment/reference/harbor_entry.py
-
curl -L -o harbor_entry.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/brooklinen/environment/reference/harbor_entry.py
11.8 kB
| #!/usr/bin/env python3 | |
| """Single-process Harbor adapter for the frozen Brooklinen clone. | |
| Registration and password-recovery mail is written only to the trial-scoped | |
| Mailpit SMTP writer injected by the harness. The candidate receives write | |
| coordinates alone; the verifier reads the message through ``mailbox_code``. | |
| """ | |
| from __future__ import annotations | |
| import hmac | |
| import os | |
| import random | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import smtplib | |
| from email.message import EmailMessage | |
| ROOT = Path(__file__).resolve().parent | |
| SITE_ID = "brooklinen" | |
| DATABASE_NAME = "brooklinen.sqlite3" | |
| DISPLAY_NAME = "Brooklinen" | |
| MAIL_TRANSPORT_CONTRACT = "WEBSITEBENCH_MAILPIT_DIRECT_WRITER_V1" | |
| health_contract = "/healthz" | |
| migration_version = 1 | |
| required_invariants = ('frozen-route-closure', 'loopback-runtime', 'local-mail') | |
| PAYMENT_ADAPTER = "local-sandbox" | |
| payment_profile = "local-sandbox" | |
| for _name in ("HOST", "PORT", "DATA_DIR", "SEED", "TZ"): | |
| if not os.environ.get(_name): | |
| raise SystemExit(f"{_name} is required") | |
| data_dir = Path(os.environ["DATA_DIR"]) | |
| if not data_dir.is_absolute(): | |
| raise SystemExit("DATA_DIR must be absolute") | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| try: | |
| random.seed(int(os.environ["SEED"])) | |
| except ValueError: | |
| raise SystemExit("SEED must be an integer") from None | |
| if hasattr(time, "tzset"): | |
| time.tzset() | |
| os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(data_dir / DATABASE_NAME) | |
| os.environ["WEBSITEBENCH_SITE_BACKEND_RUNTIME"] = str(ROOT / "backend" / "runtime.json") | |
| os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor" | |
| os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = PAYMENT_ADAPTER | |
| os.environ["WEBSITEBENCH_LOCAL_HTTP_COOKIE"] = "1" | |
| os.environ["WEBSITEBENCH_HARBOR_MIGRATION_VERSION"] = str(migration_version) | |
| os.environ["PYTHONDONTWRITEBYTECODE"] = "1" | |
| for _name in ( | |
| "STRIPE_SECRET_KEY", | |
| "STRIPE_WEBHOOK_SECRET", | |
| "STRIPE_TEST_SECRET_KEY", | |
| "STRIPE_TEST_WEBHOOK_SECRET", | |
| ): | |
| os.environ.pop(_name, None) | |
| sys.dont_write_bytecode = True | |
| sys.path.insert(0, str(ROOT / "vendor")) | |
| sys.path.insert(0, str(ROOT / "clone")) | |
| # The frozen clone resolves its own static mounts relative to the process | |
| # working directory, so the adapter enters the clone tree rather than | |
| # rewriting a pinned path. | |
| os.chdir(ROOT / "clone") | |
| import websitebench.local_clone_auth as auth_package # noqa: E402 | |
| from websitebench.local_clone_auth import store as auth_store # noqa: E402 | |
| from websitebench.local_clone_auth import AuthError # noqa: E402 | |
| _BASE_AUTH_STORE = auth_store.LocalAuthStore | |
| class MailpitAuthStore(_BASE_AUTH_STORE): | |
| """Deliver auth challenges to Mailpit without consuming the local record. | |
| This clone verifies registration itself by reading its own LOCAL_ONLY | |
| outbox row, so claiming the message or switching the store to SMTP_PENDING | |
| would break the frozen flow. Keep the row exactly as the site wrote it and | |
| send a copy through the injected SMTP writer instead. | |
| """ | |
| def _smtp_coordinates(self) -> tuple[str, int, str] | None: | |
| host = os.environ.get("WEBSITEBENCH_SMTP_HOST", "") | |
| raw_port = os.environ.get("WEBSITEBENCH_SMTP_PORT", "") | |
| sender = os.environ.get("WEBSITEBENCH_SMTP_FROM", "") | |
| if not host and not raw_port and not sender: | |
| # No trial mailbox writer is advertised at all. That is a | |
| # deployment without a Mailpit sidecar, not a rejected account: | |
| # the public registration transition still has to succeed and the | |
| # challenge simply stays pending until a writer appears. | |
| return None | |
| if host not in {"127.0.0.1", "localhost"}: | |
| raise AuthError("trial mailbox SMTP writer is unavailable") | |
| try: | |
| port = int(raw_port) | |
| except ValueError as error: | |
| raise AuthError("trial mailbox SMTP writer is unavailable") from error | |
| if not 1 <= port <= 65535 or not sender.endswith( | |
| "@candidate.websitebench.local" | |
| ): | |
| raise AuthError("trial mailbox SMTP writer is unavailable") | |
| return host, port, sender | |
| def _mirror_to_mailpit(self, session_token: str, *, purpose: str, subject: str) -> None: | |
| coordinates = self._smtp_coordinates() | |
| if coordinates is None: | |
| return | |
| host, port, sender = coordinates | |
| self.ensure_schema() | |
| with self.connect() as connection: | |
| session = self._session_row(connection, session_token) | |
| if session is None: | |
| return | |
| row = connection.execute( | |
| "SELECT flow_id,recipient FROM local_auth_mail_outbox " | |
| "WHERE session_digest=? AND purpose=? AND status='LOCAL_ONLY' " | |
| "ORDER BY mail_id DESC LIMIT 1", | |
| (session["session_digest"], purpose), | |
| ).fetchone() | |
| if row is None: | |
| return | |
| code = self._mail_code(purpose, str(row["flow_id"])) | |
| if code is None: | |
| return | |
| message = EmailMessage() | |
| message["From"] = sender | |
| message["To"] = str(row["recipient"]) | |
| message["Subject"] = subject | |
| message.set_content(f"Your {DISPLAY_NAME} {purpose} code is {code}.") | |
| try: | |
| with smtplib.SMTP(host, port, timeout=10) as smtp: | |
| if smtp.send_message(message): | |
| raise OSError("Mailpit rejected a trial recipient") | |
| except (OSError, smtplib.SMTPException) as error: | |
| raise AuthError("trial mailbox delivery was deferred") from error | |
| def start_registration(self, session_token: str, **kwargs): | |
| result = super().start_registration(session_token, **kwargs) | |
| self._mirror_to_mailpit( | |
| session_token, purpose="registration", | |
| subject="Verify your Brooklinen account", | |
| ) | |
| return result | |
| def start_password_reset(self, session_token: str, **kwargs): | |
| result = super().start_password_reset(session_token, **kwargs) | |
| self._mirror_to_mailpit( | |
| session_token, purpose="password-reset", | |
| subject="Reset your Brooklinen password", | |
| ) | |
| return result | |
| # The clone reaches its store through ``open_site_services``, which binds | |
| # ``LocalAuthStore`` by name at import time. Rebinding both the module and the | |
| # package export before the clone is imported redirects every construction | |
| # path without touching a frozen byte. | |
| auth_store.LocalAuthStore = MailpitAuthStore | |
| auth_package.LocalAuthStore = MailpitAuthStore | |
| from app import app as app # noqa: E402 | |
| from backend.site_backend_integration import ( # noqa: E402 | |
| open_site_services, | |
| ) | |
| def _reset_site_state() -> None: | |
| """Reset exactly the rows the vendored backend and auth own.""" | |
| backend, auth = open_site_services() | |
| def _site_reset(connection) -> None: | |
| backend.lifecycle.reset_embedded( | |
| connection, confirm_site_id=SITE_ID | |
| ) | |
| auth.reset_site_state(site_reset=_site_reset, seed_accounts=[]) | |
| from fastapi import Request # noqa: E402 | |
| from fastapi.responses import JSONResponse, PlainTextResponse # noqa: E402 | |
| import uvicorn # noqa: E402 | |
| async def harbor_site_header(request: Request, call_next): | |
| if request.method == "GET" and request.url.path in { | |
| "/healthz", | |
| "/__websitebench/health", | |
| }: | |
| response = JSONResponse({"status": "ok"}) | |
| else: | |
| response = await call_next(request) | |
| response.headers["X-WebsiteBench-Site"] = SITE_ID | |
| return response | |
| async def harbor_lifecycle_health() -> JSONResponse: | |
| """Expose the exact lifecycle body while preserving clone `/healthz`.""" | |
| return JSONResponse({"status": "ok"}) | |
| _health_routes = [ | |
| route | |
| for route in app.router.routes | |
| if getattr(route, "endpoint", None) is harbor_lifecycle_health | |
| ] | |
| for route in _health_routes: | |
| app.router.routes.remove(route) | |
| app.router.routes[:0] = _health_routes | |
| _ADMIN_TOKEN = os.environ.get("WEBSITEBENCH_ADMIN_TOKEN", "") | |
| _RESET_PATH = "/__admin/reset" | |
| def _declared_routes(router): | |
| """Yield (path, methods) including lazily included sub-routers. | |
| FastAPI defers ``include_router`` into an ``_IncludedRouter`` placeholder | |
| that carries no path until the first request, so a plain scan of | |
| ``app.router.routes`` reports a clone as owning far fewer routes than it | |
| does. Follow ``original_router`` so detection sees the real table. | |
| """ | |
| for route in getattr(router, "routes", ()): | |
| included = getattr(route, "original_router", None) | |
| if included is not None: | |
| yield from _declared_routes(included) | |
| continue | |
| path = getattr(route, "path", None) | |
| if isinstance(path, str): | |
| yield path, set(getattr(route, "methods", None) or ()) | |
| _clone_owns_reset = any( | |
| path == _RESET_PATH and "POST" in methods | |
| for path, methods in _declared_routes(app.router) | |
| ) | |
| if not _clone_owns_reset: | |
| async def harbor_reset(request: Request) -> JSONResponse: | |
| """Deterministic reset, admin-token guarded like the paired clones. | |
| Reset authority is never granted to an unauthenticated caller; the | |
| trial harness isolates state with a fresh ``DATA_DIR`` instead. | |
| """ | |
| supplied = request.headers.get("X-WebsiteBench-Admin-Token", "") | |
| if not _ADMIN_TOKEN or not hmac.compare_digest(supplied, _ADMIN_TOKEN): | |
| return JSONResponse({"error": "forbidden"}, status_code=403) | |
| _reset_site_state() | |
| return JSONResponse({"reset": True, "site_id": SITE_ID}) | |
| async def harbor_reset_get() -> PlainTextResponse: | |
| return PlainTextResponse("Page not found", status_code=404) | |
| # A frozen catch-all would otherwise shadow the harness ABI. Move only the | |
| # two adapter routes to the front; reordering the whole table would also | |
| # move the clone's own routes relative to each other. | |
| _added = [ | |
| route | |
| for route in app.router.routes | |
| if getattr(route, "path", None) == _RESET_PATH | |
| ] | |
| for route in _added: | |
| app.router.routes.remove(route) | |
| app.router.routes[:0] = _added | |
| def _warm_first_render() -> None: | |
| """Pay the clone's lazy first-render cost before serving traffic. | |
| The frozen storefront initialises its services, catalogue and template | |
| caches on the first rendered page, which takes far longer than any | |
| steady-state request. Drive one in-process ASGI GET so that cost lands | |
| during boot instead of inside a scored trial's first request. | |
| """ | |
| import asyncio | |
| async def _drive() -> None: | |
| async def receive(): | |
| return {"type": "http.request", "body": b"", "more_body": False} | |
| async def send(message) -> None: | |
| return None | |
| scope = { | |
| "type": "http", | |
| "asgi": {"version": "3.0", "spec_version": "2.3"}, | |
| "http_version": "1.1", | |
| "method": "GET", | |
| "path": "/", | |
| "raw_path": b"/", | |
| "root_path": "", | |
| "query_string": b"", | |
| "headers": [(b"host", b"127.0.0.1")], | |
| "scheme": "http", | |
| "client": ("127.0.0.1", 0), | |
| "server": ("127.0.0.1", 0), | |
| } | |
| await app(scope, receive, send) | |
| try: | |
| asyncio.run(_drive()) | |
| except Exception: | |
| # Warmup is best-effort; the clone still serves without it. | |
| pass | |
| if __name__ == "__main__": | |
| _warm_first_render() | |
| uvicorn.run( | |
| app, | |
| host=os.environ["HOST"], | |
| port=int(os.environ["PORT"]), | |
| log_level="warning", | |
| ) | |