File size: 11,320 Bytes
edec962
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python3
"""Single-process Harbor adapter for the frozen Curology 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 secrets
import smtplib
from email.message import EmailMessage


ROOT = Path(__file__).resolve().parent
SITE_ID = "curology"
DATABASE_NAME = "curology.sqlite3"
DISPLAY_NAME = "Curology"
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 (  # noqa: E402
    MAIL_SMTP_PENDING,
    AuthError,
)

_BASE_AUTH_STORE = auth_store.LocalAuthStore
_MAIL_WORKER_TOKEN = secrets.token_urlsafe(48)


class MailpitAuthStore(_BASE_AUTH_STORE):
    """Deliver auth challenges only through the injected Mailpit SMTP writer."""

    def __init__(self, database_path, **kwargs):
        kwargs["mail_mode"] = MAIL_SMTP_PENDING
        kwargs["mail_worker_token"] = _MAIL_WORKER_TOKEN
        super().__init__(database_path, **kwargs)

    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 _deliver_mailpit(
        self, session_token: str, *, purpose: str, subject: str
    ) -> None:
        coordinates = self._smtp_coordinates()
        if coordinates is None:
            return
        host, port, sender = coordinates
        claim = self.claim_pending_mail_for_session(
            session_token,
            purpose=purpose,
            worker_token=_MAIL_WORKER_TOKEN,
        )
        # Password reset stays non-enumerating: an unknown account produces no
        # message but follows the same browser transition.
        if claim is None:
            return
        mail_id = int(claim["mail_id"])
        claim_token = str(claim["claim_token"])
        self.reserve_mail_target_request(
            mail_id, claim_token, worker_token=_MAIL_WORKER_TOKEN
        )
        message = EmailMessage()
        message["From"] = sender
        message["To"] = str(claim["recipient"])
        message["Subject"] = subject
        message.set_content(
            f"Your {DISPLAY_NAME} {purpose} code is {claim['verification_code']}."
        )
        try:
            with smtplib.SMTP(host, port, timeout=10) as smtp:
                refused = smtp.send_message(message)
            if refused:
                raise OSError("Mailpit rejected a trial recipient")
        except (OSError, smtplib.SMTPException) as error:
            self.finish_mail_claim(
                mail_id,
                claim_token,
                sent=False,
                target_request_count=1,
                accepted_request_count=0,
                error="network",
                worker_token=_MAIL_WORKER_TOKEN,
            )
            raise AuthError("trial mailbox delivery was deferred") from error
        self.finish_mail_claim(
            mail_id,
            claim_token,
            sent=True,
            target_request_count=1,
            accepted_request_count=1,
            worker_token=_MAIL_WORKER_TOKEN,
        )

    def start_registration(self, session_token: str, **kwargs):
        result = super().start_registration(session_token, **kwargs)
        self._deliver_mailpit(
            session_token,
            purpose="registration",
            subject="Verify your Curology account",
        )
        return result

    def start_password_reset(self, session_token: str, **kwargs):
        result = super().start_password_reset(session_token, **kwargs)
        self._deliver_mailpit(
            session_token,
            purpose="password-reset",
            subject="Reset your Curology 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


@app.middleware("http")
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


@app.get("/__websitebench/health", include_in_schema=False)
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:

    @app.post(_RESET_PATH, include_in_schema=False)
    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})

    @app.get(_RESET_PATH, include_in_schema=False)
    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

if __name__ == "__main__":
    # The frozen clone builds its service singleton (schema, demo seed, KDF
    # work) lazily on the first page hit, which takes tens of seconds cold.
    # Warm it before serving so the first real request answers promptly.
    import app as _clone_app_module  # noqa: E402

    _clone_app_module.services()
    uvicorn.run(
        app,
        host=os.environ["HOST"],
        port=int(os.environ["PORT"]),
        log_level="warning",
    )