File size: 9,762 Bytes
5b847ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Single-process Harbor adapter for the frozen Dooney & Bourke 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 = "dooney-bourke"
DATABASE_NAME = "dooney-bourke.sqlite3"
DISPLAY_NAME = "Dooney & Bourke"
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 Dooney & Bourke 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 Dooney & Bourke 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 application 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=[])


# --- WSGI variant ------------------------------------------------------------
# The frozen Dooney & Bourke clone is a plain WSGI callable served by wsgiref;
# it has no FastAPI/Starlette router to decorate. The same harness ABI is
# attached through a thin WSGI wrapper instead: the clone already answers
# ``/healthz`` and ``/__websitebench/health`` itself, so the wrapper only adds
# the admin-token-guarded ``/__admin/reset`` route and the
# ``X-WebsiteBench-Site`` response header.
import json as _json  # noqa: E402

import uvicorn  # noqa: E402

_ADMIN_TOKEN = os.environ.get("WEBSITEBENCH_ADMIN_TOKEN", "")
_RESET_PATH = "/__admin/reset"
_clone_application = app


def _harbor_wsgi(environ, start_response):
    path = environ.get("PATH_INFO", "")
    method = environ.get("REQUEST_METHOD", "").upper()
    if path == _RESET_PATH:
        base_headers = [
            ("X-WebsiteBench-Site", SITE_ID),
        ]
        if method != "POST":
            start_response(
                "404 Not Found",
                [("Content-Type", "text/plain; charset=utf-8"), *base_headers],
            )
            return [b"Page not found"]
        supplied = environ.get("HTTP_X_WEBSITEBENCH_ADMIN_TOKEN", "")
        if not _ADMIN_TOKEN or not hmac.compare_digest(supplied, _ADMIN_TOKEN):
            start_response(
                "403 Forbidden",
                [("Content-Type", "application/json"), *base_headers],
            )
            return [b'{"error": "forbidden"}']
        _reset_site_state()
        start_response(
            "200 OK",
            [("Content-Type", "application/json"), *base_headers],
        )
        return [_json.dumps({"reset": True, "site_id": SITE_ID}).encode("utf-8")]

    def _start(status, headers, exc_info=None):
        amended = list(headers)
        amended.append(("X-WebsiteBench-Site", SITE_ID))
        return start_response(status, amended, exc_info)

    return _clone_application(environ, _start)


app = _harbor_wsgi

if __name__ == "__main__":
    uvicorn.run(
        app,
        host=os.environ["HOST"],
        port=int(os.environ["PORT"]),
        log_level="warning",
        interface="wsgi",
    )