File size: 7,395 Bytes
3f893e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Single-process Harbor adapter for the frozen autoslash clone.

An unscored agent environment with trial-local mail and simulated payments.
"""

from __future__ import annotations


import os
import random
import sys
import time
from pathlib import Path

import secrets

ROOT = Path(__file__).resolve().parent
SITE_ID = "autoslash"
DATABASE_NAME = "autoslash.sqlite3"
DISPLAY_NAME = "autoslash"
MAIL_TRANSPORT_CONTRACT = "websitebench.resend-style-text.v1"
health_contract = "/healthz"
migration_version = 1
required_invariants = ('site-isolation', 'persistent-data', 'browser-mailbox')
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)


def _send_trial_message(recipient, subject, text):
    import json
    from urllib.parse import urlsplit
    from urllib.request import Request, urlopen
    endpoint = os.environ.get('WEBSITEBENCH_MAIL_API_URL', '')
    token = os.environ.get('WEBSITEBENCH_MAIL_API_TOKEN', '')
    sender = os.environ.get('WEBSITEBENCH_MAIL_FROM', '')
    parsed = urlsplit(endpoint)
    if parsed.scheme != 'http' or parsed.hostname not in {'mailbox-internal', 'localhost', '127.0.0.1'} or parsed.path != '/emails' or parsed.username or parsed.password or not token or not sender:
        raise AuthError('Trial mail writer is unavailable')
    body = json.dumps({'from': sender, 'to': recipient, 'subject': subject, 'text': text}).encode()
    request = Request(endpoint, data=body, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}, method='POST')
    with urlopen(request, timeout=10) as response:
        if not 200 <= response.status < 300:
            raise AuthError('Trial mail writer rejected the message')
        response.read(65536)


class MailpitAuthStore(_BASE_AUTH_STORE):
    """Claim once and send through the trial's canonical write-only mail API."""
    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 _deliver(self, session_token, purpose):
        import json
        from urllib.parse import urlsplit
        from urllib.request import Request, urlopen
        endpoint = os.environ.get('WEBSITEBENCH_MAIL_API_URL', '')
        token = os.environ.get('WEBSITEBENCH_MAIL_API_TOKEN', '')
        sender = os.environ.get('WEBSITEBENCH_MAIL_FROM', '')
        parsed = urlsplit(endpoint)
        if parsed.scheme != 'http' or parsed.hostname not in {'mailbox-internal', 'localhost', '127.0.0.1'} or parsed.path != '/emails' or parsed.username or parsed.password or not token or not sender:
            raise AuthError('Trial mail writer is unavailable')
        claim = self.claim_pending_mail_for_session(session_token, purpose=purpose, worker_token=_MAIL_WORKER_TOKEN)
        if claim is None:
            return
        mail_id, claim_token = int(claim['mail_id']), claim['claim_token']
        self.reserve_mail_target_request(mail_id, claim_token, worker_token=_MAIL_WORKER_TOKEN)
        body = json.dumps({'from': sender, 'to': claim['recipient'], 'subject': DISPLAY_NAME + ' ' + purpose, 'text': 'Your verification code is ' + claim['verification_code'] + '.'}).encode()
        request = Request(endpoint, data=body, headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}, method='POST')
        try:
            with urlopen(request, timeout=10) as response:
                if not 200 <= response.status < 300:
                    raise OSError('Mail writer rejected the message')
                response.read(65536)
        except Exception:
            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('Mail delivery is unavailable. Please retry.') from None
        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, **kwargs):
        result = super().start_registration(session_token, **kwargs)
        self._deliver(session_token, 'registration')
        return result

    def start_password_reset(self, session_token, **kwargs):
        result = super().start_password_reset(session_token, **kwargs)
        self._deliver(session_token, 'password-reset')
        return result

auth_store.LocalAuthStore = MailpitAuthStore
auth_package.LocalAuthStore = MailpitAuthStore

import app as clone
app = clone.app


import uvicorn
_application = app
async def app(scope, receive, send):
    if scope['type'] == 'http':
        async def site_send(message):
            if message['type'] == 'http.response.start':
                message = dict(message)
                message['headers'] = [(k,v) for k,v in message.get('headers', []) if k.lower() != b'x-websitebench-site'] + [(b'x-websitebench-site', SITE_ID.encode())]
            await send(message)
        if scope['method'] == 'GET' and scope['path'] in {'/healthz', '/__websitebench/health'}:
            await site_send({'type':'http.response.start','status':200,'headers':[(b'content-type',b'application/json')]})
            await send({'type':'http.response.body','body':b'{"status":"ok"}'})
        else:
            await _application(scope, receive, site_send)
    else:
        await _application(scope, receive, send)

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