File size: 5,536 Bytes
34be7eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
from __future__ import annotations

import json
import os
import random
import sys
import time
from http.server import ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit

ROOT = Path(__file__).resolve().parent

SITE_ID = "freshdirect"
DATABASE_NAME = "freshdirect.sqlite3"
# The session identity this adapter runs with.  Harbor reads the cookie off the
# wire; this names the same contract in the executable and fails the runtime
# closed if the projected backend ever stops scoping the session to this site
# or stops hardening it.
freshdirect_session_cookie = "websitebench-freshdirect-session"
freshdirect_session_policy = dict(httponly=True, samesite="lax", path="/")
PAYMENT_ADAPTER = "disabled"
payment_profile = "no-payment-external-effects"
FORBIDDEN_PAYMENT_ADAPTERS = ("local-sandbox", "stripe-test", "live")
MAIL_TRANSPORT = "disabled-no-reachable-mail-flow"
migration_version = 1
status_code = 200
required_invariants = (
    "freshdirect.runtime-network-closed",
    "freshdirect.catalog-discovery-operable",
    "freshdirect.availability-and-cart-authoritative",
)
if PAYMENT_ADAPTER in FORBIDDEN_PAYMENT_ADAPTERS:
    raise SystemExit("FreshDirect payments must remain disabled")
contract_headers = {
    "X-WebsiteBench-Site": SITE_ID,
    "X-WebsiteBench-Database": DATABASE_NAME,
    "X-WebsiteBench-Migration": str(migration_version),
    "X-WebsiteBench-Payment-Adapter": PAYMENT_ADAPTER,
    "X-WebsiteBench-Mail-Transport": MAIL_TRANSPORT,
}

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_LOCAL_HTTP_COOKIE"] = "1"
os.environ["WEBSITEBENCH_DEPLOYMENT_PROFILE"] = "offline-harbor"
os.environ["WEBSITEBENCH_PAYMENT_PROFILE"] = PAYMENT_ADAPTER
os.environ["WEBSITEBENCH_DATA_DIR"] = str(data_dir)
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 / "clone"))

from websitebench.site_backend.runtime import load_runtime  # noqa: E402

_session_contract = load_runtime(ROOT / "backend" / "runtime.json")
if _session_contract.cookie_name.removeprefix("__Host-") != freshdirect_session_cookie:
    raise SystemExit("FreshDirect session cookie is not scoped to this site")
_session_options = _session_contract.cookie_options
if not _session_options["httponly"] or str(
    _session_options["samesite"]
).lower() != freshdirect_session_policy["samesite"]:
    raise SystemExit("FreshDirect session cookie is not hardened")
if _session_options["path"] != freshdirect_session_policy["path"]:
    raise SystemExit("FreshDirect session cookie is not host-scoped to the root path")

# The frozen clone resolves its files relative to its own location, but enter
# the clone tree anyway so any cwd-relative lookup stays inside it.
os.chdir(ROOT / "clone")

import app as clone_app  # noqa: E402

HEALTH_PATHS = {"/healthz", "/__websitebench/health"}
_FrozenHandler = clone_app.App


def _send_json(handler: Any, status: int, payload: dict[str, Any]) -> None:
    body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
    handler.send_response(status)
    handler.send_header("Content-Type", "application/json; charset=utf-8")
    handler.send_header("Content-Length", str(len(body)))
    handler.send_header("Cache-Control", "no-store")
    handler.end_headers()
    if handler.command != "HEAD":
        handler.wfile.write(body)


class HarborHandler(_FrozenHandler):
    """The frozen clone handler plus the Harbor contract headers and health.

    Every response of the frozen handler passes through ``send_response``, so
    the proof headers ride along without editing a frozen byte; the two health
    paths answer the exact body the executor waits for before any case runs.
    """

    def send_response(self, code: int, message: Any = None) -> None:  # noqa: N802
        super().send_response(code, message)
        for name, value in contract_headers.items():
            self.send_header(name, value)
        if urlsplit(self.path).path not in HEALTH_PATHS:
            self.send_header("X-WebsiteBench-Invariants", ",".join(required_invariants))

    def do_GET(self) -> None:  # noqa: N802
        if urlsplit(self.path).path in HEALTH_PATHS:
            return _send_json(self, 200, {"status": "ok"})
        return super().do_GET()

    def do_HEAD(self) -> None:  # noqa: N802
        if urlsplit(self.path).path in HEALTH_PATHS:
            return _send_json(self, 200, {"status": "ok"})
        parent = getattr(super(), "do_HEAD", None)
        if parent is None:
            return self.send_error(501)
        return parent()


if __name__ == "__main__":
    server = ThreadingHTTPServer((os.environ["HOST"], int(os.environ["PORT"])), HarborHandler)
    server.daemon_threads = True
    server.serve_forever()