Download tasks/ioby/tests/oracle-runtime/harbor_entry.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/ioby/tests/oracle-runtime/harbor_entry.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/ioby/tests/oracle-runtime/harbor_entry.py
-
curl -L -o harbor_entry.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/ioby/tests/oracle-runtime/harbor_entry.py
10.3 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import urllib.parse | |
| import urllib.request | |
| from contextvars import ContextVar | |
| from pathlib import Path | |
| from typing import Any | |
| import uvicorn | |
| from fastapi import Request | |
| from starlette.responses import JSONResponse, Response | |
| from websitebench.local_clone_auth.store import LocalAuthStore | |
| ROOT = Path(__file__).resolve().parent | |
| SITE_ID = "ioby" | |
| DATABASE_NAME = "ioby.sqlite3" | |
| data_dir = Path(os.environ["DATA_DIR"]).resolve() | |
| migration_version = 1 | |
| REQUIRED_INVARIANTS = ( | |
| "runtime.local-only", | |
| "project.source-grounded", | |
| "ioby.mailpit-only-mail", | |
| "payment.local-sandbox", | |
| "account.site-isolated", | |
| ) | |
| required_invariants = REQUIRED_INVARIANTS | |
| PAYMENT_ADAPTER = "local-sandbox" | |
| MAILPIT_DIRECT_WRITER = "WEBSITEBENCH_MAILPIT_DIRECT_WRITER_V1" | |
| status_code = 200 | |
| data_dir.mkdir(parents=True, exist_ok=True) | |
| runtime_contract = json.loads( | |
| (ROOT / "backend/runtime.json").read_text(encoding="utf-8") | |
| ) | |
| if ( | |
| runtime_contract.get("site", {}).get("id") != SITE_ID | |
| or runtime_contract.get("database", {}).get("filename") != DATABASE_NAME | |
| ): | |
| raise RuntimeError("assembled backend runtime does not match the site contract") | |
| def _mailpit_writer() -> tuple[str, str, str]: | |
| url = os.environ.get("WEBSITEBENCH_MAIL_API_URL", "").strip() | |
| token = os.environ.get("WEBSITEBENCH_MAIL_API_TOKEN", "").strip() | |
| sender = os.environ.get("WEBSITEBENCH_MAIL_FROM", "").strip() | |
| parsed = urllib.parse.urlsplit(url) | |
| if ( | |
| parsed.scheme != "http" | |
| or parsed.hostname not in {"127.0.0.1", "localhost", "::1", "mailbox-internal"} | |
| or not token | |
| or not sender | |
| ): | |
| raise RuntimeError("Mailpit-backed candidate writer is unavailable") | |
| return url, token, sender | |
| def _send_code(recipient: str, code: str, purpose: str) -> None: | |
| url, token, sender = _mailpit_writer() | |
| declared = runtime_contract.get("mail", {}).get("purposes", {}).get(purpose) | |
| if not isinstance(declared, dict): | |
| raise ValueError("unsupported mail purpose") | |
| text = "\n\n".join( | |
| ( | |
| str(declared["lead"]), | |
| str(declared["body"]).replace("${code}", code), | |
| str(declared["expiry"]).replace("${minutes}", "15"), | |
| str(declared["footer"]), | |
| ) | |
| ) | |
| payload = json.dumps( | |
| { | |
| "from": sender, | |
| "to": recipient, | |
| "subject": str(declared["subject"]), | |
| "text": text, | |
| }, | |
| separators=(",", ":"), | |
| ).encode() | |
| request = urllib.request.Request( | |
| url, | |
| data=payload, | |
| method="POST", | |
| headers={ | |
| "Authorization": "Bearer " + token, | |
| "Content-Type": "application/json", | |
| }, | |
| ) | |
| with urllib.request.urlopen(request, timeout=5) as response: | |
| if not 200 <= response.status < 300: | |
| raise RuntimeError("Mailpit-backed candidate writer rejected message") | |
| _active_delivery: ContextVar[dict[str, str] | None] = ContextVar( | |
| "ioby_mailpit_delivery", default=None | |
| ) | |
| _pending_mail_view: ContextVar[str | None] = ContextVar( | |
| "ioby_pending_mail_view", default=None | |
| ) | |
| _original_start_registration = LocalAuthStore.start_registration | |
| _original_start_password_reset = LocalAuthStore.start_password_reset | |
| def _suppress_outbox(self: LocalAuthStore, *args: Any, **kwargs: Any) -> None: | |
| if _active_delivery.get() is None: | |
| raise RuntimeError("mail creation requires an active Mailpit delivery") | |
| def _capture_code(self: LocalAuthStore, purpose: str, flow_id: str, code: str) -> None: | |
| active = _active_delivery.get() | |
| if active is None: | |
| raise RuntimeError("mail code capture requires an active Mailpit delivery") | |
| active.update({"purpose": purpose, "flow_id": flow_id, "code": code}) | |
| def _disable_local_reader( | |
| self: LocalAuthStore, session_token: str, *, purpose: str | |
| ) -> None: | |
| # The clone calls this legacy seam only to decide which form to render. | |
| # Preserve that UI transition without reading or returning mail data. | |
| _pending_mail_view.set(purpose) | |
| return None | |
| def _start_registration( | |
| self: LocalAuthStore, | |
| session_token: str, | |
| *, | |
| email: str, | |
| display_name: str, | |
| password: str, | |
| restart_invalid_flow: bool = False, | |
| ) -> dict[str, Any]: | |
| active: dict[str, str] = {} | |
| context = _active_delivery.set(active) | |
| try: | |
| result = _original_start_registration( | |
| self, | |
| session_token, | |
| email=email, | |
| display_name=display_name, | |
| password=password, | |
| restart_invalid_flow=restart_invalid_flow, | |
| ) | |
| code = active.get("code") | |
| if not code: | |
| raise RuntimeError("registration did not generate a Mailpit code") | |
| _send_code(email.strip().casefold(), code, "registration") | |
| return {**result, "mail_status": "MAILPIT_SENT"} | |
| finally: | |
| active.clear() | |
| _active_delivery.reset(context) | |
| def _start_password_reset( | |
| self: LocalAuthStore, | |
| session_token: str, | |
| *, | |
| email: str, | |
| restart_invalid_flow: bool = False, | |
| ) -> dict[str, Any]: | |
| active: dict[str, str] = {} | |
| context = _active_delivery.set(active) | |
| try: | |
| result = _original_start_password_reset( | |
| self, | |
| session_token, | |
| email=email, | |
| restart_invalid_flow=restart_invalid_flow, | |
| ) | |
| code = active.get("code") | |
| if code is not None: | |
| _send_code(email.strip().casefold(), code, "password-reset") | |
| return result | |
| finally: | |
| active.clear() | |
| _active_delivery.reset(context) | |
| LocalAuthStore._insert_mail_unlocked = _suppress_outbox | |
| LocalAuthStore._remember_mail_code = _capture_code | |
| LocalAuthStore.local_mail_for_session = _disable_local_reader | |
| LocalAuthStore.start_registration = _start_registration | |
| LocalAuthStore.start_password_reset = _start_password_reset | |
| from app import APP as app, AUTH, BACKEND # noqa: E402 | |
| from backend import business # noqa: E402 | |
| import views as clone_views # noqa: E402 | |
| _original_register_view = clone_views.register | |
| _original_recover_view = clone_views.recover | |
| def _mailpit_input(markup: str, *, purpose: str) -> str: | |
| markup = re.sub( | |
| r'<output class="local-code"[^>]*>MAILPIT_CODE_INPUT</output>', | |
| ( | |
| '<p class="notice" role="status">Check the isolated Mailpit ' | |
| f"mailbox for the fresh {purpose} code.</p>" | |
| ), | |
| markup, | |
| ) | |
| return ( | |
| markup.replace("LOCAL OUTBOX", "ISOLATED MAILPIT") | |
| .replace( | |
| "No email was sent. For this offline simulation, use the code shown below.", | |
| "A fresh code was sent to the isolated Mailpit mailbox.", | |
| ) | |
| .replace( | |
| "No real email is sent. A code is exposed only in this browser's local outbox.", | |
| "No external email is sent. The fresh code is available only through the isolated Mailpit mailbox.", | |
| ) | |
| .replace( | |
| "Verification stays in the local outbox.", | |
| "Verification uses the isolated Mailpit mailbox.", | |
| ) | |
| ) | |
| def _register_view(*, values: Any = None, error: str = "", code: str = "") -> str: | |
| pending = _pending_mail_view.get() | |
| if values or error or code or pending == "registration": | |
| _pending_mail_view.set(None) | |
| return _mailpit_input( | |
| _original_register_view( | |
| values=values, error=error, code="MAILPIT_CODE_INPUT" | |
| ), | |
| purpose="registration", | |
| ) | |
| return _mailpit_input(_original_register_view(), purpose="registration") | |
| def _recover_view(*, message: str = "", error: str = "", code: str = "") -> str: | |
| pending = _pending_mail_view.get() | |
| if message or error or code or pending == "password-reset": | |
| _pending_mail_view.set(None) | |
| return _mailpit_input( | |
| _original_recover_view( | |
| message=message, error=error, code="MAILPIT_CODE_INPUT" | |
| ), | |
| purpose="password-reset", | |
| ) | |
| return _mailpit_input(_original_recover_view(), purpose="password-reset") | |
| clone_views.register = _register_view | |
| clone_views.recover = _recover_view | |
| def _reset_site() -> None: | |
| BACKEND.lifecycle.reset(confirm_site_id=SITE_ID) | |
| BACKEND.lifecycle.initialize() | |
| AUTH.ensure_schema() | |
| account_id = AUTH.seed_account( | |
| subject_id="ioby-demo-neighbor", | |
| email="demo@ioby.local", | |
| display_name="Morgan Neighbor", | |
| password="Neighbor123!", | |
| ) | |
| with BACKEND.lifecycle.connection(transaction=True) as connection: | |
| business.migrate(connection) | |
| business.seed_demo(connection, account_id) | |
| def _headers(response: Response) -> Response: | |
| response.headers["X-WebsiteBench-Site"] = SITE_ID | |
| response.headers["X-WebsiteBench-Database"] = DATABASE_NAME | |
| response.headers["X-WebsiteBench-Migration"] = str(migration_version) | |
| response.headers["X-WebsiteBench-Invariants"] = ",".join(REQUIRED_INVARIANTS) | |
| response.headers["X-WebsiteBench-Payment-Adapter"] = PAYMENT_ADAPTER | |
| response.headers["X-WebsiteBench-Mail-Transport"] = MAILPIT_DIRECT_WRITER | |
| return response | |
| async def harbor_contract(request: Request, call_next: Any) -> Response: | |
| if request.method == "GET" and request.url.path in { | |
| "/healthz", | |
| "/__websitebench/health", | |
| }: | |
| return _headers(JSONResponse({"status": "ok"})) | |
| if request.url.path == "/__admin/reset": | |
| expected = os.environ.get("WEBSITEBENCH_ADMIN_TOKEN", "") | |
| supplied = request.headers.get("X-WebsiteBench-Admin-Token", "") | |
| if request.method != "POST" or not expected or supplied != expected: | |
| return _headers(JSONResponse({"error": "unauthorized"}, status_code=401)) | |
| _reset_site() | |
| return _headers(JSONResponse({"status": "reset"})) | |
| response = await call_next(request) | |
| if status_code != 200 and request.url.path != "/" + "healthz": | |
| response.status_code = status_code | |
| return _headers(response) | |
| if __name__ == "__main__": | |
| uvicorn.run( | |
| app, | |
| host=os.environ.get("HOST", "127.0.0.1"), | |
| port=int(os.environ.get("PORT", "8080")), | |
| log_level="warning", | |
| ) | |