File size: 7,287 Bytes
5961e41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import json
import os
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 = "insureon"
DATABASE_NAME = "insureon.sqlite3"
data_dir = Path(os.environ["DATA_DIR"]).resolve()
migration_version = 1
REQUIRED_INVARIANTS = (
    "insureon.frozen-route-closure",
    "insureon.account-business-isolation",
    "insureon.mailpit-only-mail",
    "insureon.local-sandbox-policy-payment",
)
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")
    subject = str(declared["subject"])
    lead = str(declared["lead"])
    body = str(declared["body"]).replace("${code}", code)
    expiry = str(declared["expiry"]).replace("${minutes}", "15")
    footer = str(declared["footer"])
    text = "\n\n".join((lead, body, expiry, footer))
    payload = json.dumps(
        {"from": sender, "to": recipient, "subject": 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(
    "insureon_mailpit_delivery", 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:
    """Formal direct flows never create clone-local mail rows."""

    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:
    """Keep the generated OTP only in the active call frame until delivery."""

    active = _active_delivery.get()
    if active is not None:
        active.update({"purpose": purpose, "flow_id": flow_id, "code": code})
    else:
        raise RuntimeError("mail code capture requires an active Mailpit delivery")


def _disable_local_reader(
    self: LocalAuthStore, session_token: str, *, purpose: str
) -> None:
    """Candidate code has no mail-reading surface."""

    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, _seed_fixtures  # noqa: E402

# The clone's own diagnostic seed establishes a deterministic public quote
# fixture used by the trusted business/payment route probes.
_seed_fixtures()


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


@APP.middleware("http")
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 in {"/api/account/local-mail", "/account/local-mail"}:
        return _headers(
            JSONResponse({"error": "mail-reader-disabled"}, status_code=404)
        )
    return _headers(await call_next(request))


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",
    )