File size: 7,866 Bytes
a6ab5dc | 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 | #!/usr/bin/env python3
"""Single-process Harbor adapter for the frozen Columbia Sportswear clone.
The frozen clone exposes site-local session and business-state behavior but no
reachable mail-producing flow. This adapter does not add a private registration,
password-reset, outbox, or mailbox surface.
"""
from __future__ import annotations
import hmac
import os
import random
import secrets
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parent
SITE_ID = "columbia"
DATABASE_NAME = "columbia.sqlite3"
DISPLAY_NAME = "Columbia Sportswear"
health_contract = "/healthz"
migration_version = 1
required_invariants = ('frozen-route-closure', 'loopback-runtime', 'site-session')
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")
# The frozen clone binds its cart database from the clone tree
# (``site/session.py`` resolves ``backend/runtime.json``'s relative
# ``data_dir`` against the clone root). The trial contract instead requires
# every mutable byte to live beneath ``DATA_DIR``, so rebind the one seam the
# clone reads its database path through before the app import constructs the
# cart service. No frozen byte changes.
sys.path.insert(0, str(ROOT / "clone" / "site"))
import session as _clone_session # noqa: E402
_clone_session._database_path = lambda: data_dir / DATABASE_NAME
from backend.site_backend_integration import ( # noqa: E402
open_site_services,
)
# Create and stamp the site-bound database beneath DATA_DIR before the clone
# constructs its cart service against the same file.
open_site_services()
from app import app as app # noqa: E402
def _reset_site_state() -> None:
"""Reset exactly the rows the vendored backend, auth, and cart own."""
backend, auth = open_site_services()
def _site_reset(connection) -> None:
backend.lifecycle.reset_embedded(
connection, confirm_site_id=SITE_ID
)
# The clone's own business tables share the bound database; a reset
# returns the cart to the seeded empty-bag baseline.
for _table in ("cart_item", "applied_promo"):
connection.execute(f"DELETE FROM {_table}")
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
_SESSION_COOKIE = f"__Host-websitebench-{SITE_ID}-session"
@app.middleware("http")
async def harbor_host_session(request: Request, call_next):
"""Issue the production-shaped host-only session cookie.
The frozen clone scopes its cart with a plain host cookie; the trial
session contract additionally expects an opaque ``__Host-`` cookie, so the
adapter issues an anonymous one alongside without touching clone state.
"""
response = await call_next(request)
if _SESSION_COOKIE not in request.cookies:
response.headers.append(
"set-cookie",
f"{_SESSION_COOKIE}={secrets.token_hex(16)}; "
"Secure; HttpOnly; Path=/; SameSite=Lax",
)
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__":
uvicorn.run(
app,
host=os.environ["HOST"],
port=int(os.environ["PORT"]),
log_level="warning",
)
|