File size: 23,602 Bytes
9eee17e | 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 | """Parse the one frozen runtime contract used by every backend adapter."""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from string import Template
from types import MappingProxyType
from typing import Any, Mapping
from urllib.parse import urlsplit
from .errors import RuntimeContractError
RUNTIME_SCHEMA_VERSION = "websitebench.site-backend-runtime.v1"
SITE_ID_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
VOLUME_IDENTITY_RE = re.compile(
r"^websitebench-[a-z0-9]+(?:-[a-z0-9]+)*-data$"
)
TEMPLATE_ID_RE = re.compile(r"^[a-z0-9]+(?:[._-][a-z0-9]+)*$")
ENV_NAME_RE = re.compile(r"^[A-Z][A-Z0-9_]{1,99}$")
CURRENCY_RE = re.compile(r"^[A-Z]{3}$")
SCENARIO_ID_RE = re.compile(r"^[a-z0-9]+(?:[._-][a-z0-9]+)*$")
def _object(value: Any, label: str, keys: set[str]) -> dict[str, Any]:
if not isinstance(value, dict):
raise RuntimeContractError(f"{label} must be an object")
unknown = set(value) - keys
if unknown:
raise RuntimeContractError(f"{label} has unknown fields: {sorted(unknown)}")
return value
def _required(value: Mapping[str, Any], label: str, keys: set[str]) -> None:
missing = keys - set(value)
if missing:
raise RuntimeContractError(f"{label} is missing fields: {sorted(missing)}")
def _text(
value: Any,
label: str,
*,
minimum: int = 1,
maximum: int = 500,
) -> str:
if (
not isinstance(value, str)
or len(value) < minimum
or len(value) > maximum
or value != value.strip()
or "\x00" in value
or "\r" in value
):
raise RuntimeContractError(f"{label} must be bounded trimmed text")
return value
def _bool(value: Any, label: str, expected: bool | None = None) -> bool:
if not isinstance(value, bool):
raise RuntimeContractError(f"{label} must be boolean")
if expected is not None and value is not expected:
raise RuntimeContractError(f"{label} must be {str(expected).lower()}")
return value
def _safe_relative_path(value: Any, label: str, *, basename: bool = False) -> str:
text = _text(value, label, maximum=240)
if "\\" in text or ":" in text or text.startswith("/"):
raise RuntimeContractError(f"{label} must be a safe relative path")
path = PurePosixPath(text)
if any(part in {"", ".", ".."} for part in path.parts):
raise RuntimeContractError(f"{label} must be a safe relative path")
if basename and len(path.parts) != 1:
raise RuntimeContractError(f"{label} must be a filename")
return text
def _https_origin(value: Any, label: str) -> str:
text = _text(value, label, maximum=300)
parsed = urlsplit(text)
if (
parsed.scheme != "https"
or not parsed.hostname
or parsed.username
or parsed.password
or parsed.port not in {None, 443}
or parsed.path not in {"", "/"}
or parsed.query
or parsed.fragment
):
raise RuntimeContractError(f"{label} must be an https origin")
return f"https://{parsed.hostname.lower()}"
def _return_path(value: Any, label: str) -> str:
text = _text(value, label, maximum=300)
parsed = urlsplit(text)
if (
not text.startswith("/")
or text.startswith("//")
or parsed.scheme
or parsed.netloc
or parsed.query
or parsed.fragment
or "\\" in text
or any(part == ".." for part in PurePosixPath(parsed.path).parts)
):
raise RuntimeContractError(f"{label} must be a safe local path")
return text
@dataclass(frozen=True)
class RuntimeConfig:
"""Validated, immutable runtime facts."""
source_path: Path | None
site_id: str
site_label: str
public_origin: str
data_dir: str
database_filename: str
volume_identity: str
migration_hook: str | None
seed_hook: str | None
legacy_unbound_migration: bool
session: Mapping[str, Any]
mail: Mapping[str, Any]
payments: Mapping[str, Any]
deployment: Mapping[str, Any]
raw: Mapping[str, Any]
@property
def site_root(self) -> Path | None:
if self.source_path is None:
return None
parent = self.source_path.parent
return parent.parent if parent.name == "backend" else parent
@property
def cookie_name(self) -> str:
return f"__Host-websitebench-{self.site_id}-session"
@property
def cookie_options(self) -> Mapping[str, Any]:
return MappingProxyType(
{
"secure": True,
"httponly": True,
"samesite": self.session["same_site"],
"path": "/",
}
)
def _validate_mail(value: Any) -> dict[str, Any]:
mail = _object(value, "mail", {"enabled", "sender", "purposes"})
_required(mail, "mail", {"sender", "purposes"})
enabled = _bool(mail.get("enabled", True), "mail.enabled")
sender = _object(
mail["sender"], "mail.sender", {"display_name", "address_env"}
)
_required(sender, "mail.sender", {"display_name", "address_env"})
sender["display_name"] = _text(
sender["display_name"], "mail.sender.display_name", maximum=120
)
address_env = _text(sender["address_env"], "mail.sender.address_env")
if not ENV_NAME_RE.fullmatch(address_env):
raise RuntimeContractError("mail.sender.address_env is invalid")
purposes = mail["purposes"]
if not isinstance(purposes, dict) or (enabled and not purposes):
raise RuntimeContractError(
"mail.purposes must be a non-empty object when mail is enabled"
)
if not enabled and purposes:
raise RuntimeContractError("mail.purposes must be empty when mail is disabled")
normalized: dict[str, Any] = {}
for purpose, raw_template in purposes.items():
if not TEMPLATE_ID_RE.fullmatch(str(purpose)):
raise RuntimeContractError("mail purpose is invalid")
template = _object(
raw_template,
f"mail.purposes.{purpose}",
{
"template_id",
"subject",
"lead",
"body",
"expiry",
"footer",
"required_variables",
"secret_variables",
},
)
_required(
template,
f"mail.purposes.{purpose}",
{
"template_id",
"subject",
"lead",
"body",
"expiry",
"footer",
"required_variables",
"secret_variables",
},
)
template_id = _text(
template["template_id"],
f"mail.purposes.{purpose}.template_id",
maximum=120,
)
if not TEMPLATE_ID_RE.fullmatch(template_id):
raise RuntimeContractError(f"mail template_id for {purpose} is invalid")
for field, maximum in (
("subject", 200),
("lead", 1000),
("body", 4000),
("expiry", 1000),
("footer", 1000),
):
template[field] = _text(
template[field],
f"mail.purposes.{purpose}.{field}",
maximum=maximum,
)
required_variables = template["required_variables"]
secret_variables = template["secret_variables"]
if (
not isinstance(required_variables, list)
or not all(
isinstance(item, str) and item.isidentifier()
for item in required_variables
)
or len(set(required_variables)) != len(required_variables)
):
raise RuntimeContractError(
f"mail.purposes.{purpose}.required_variables is invalid"
)
if (
not isinstance(secret_variables, list)
or not all(item in required_variables for item in secret_variables)
or len(set(secret_variables)) != len(secret_variables)
):
raise RuntimeContractError(
f"mail.purposes.{purpose}.secret_variables is invalid"
)
joined = "\n".join(
template[field]
for field in ("subject", "lead", "body", "expiry", "footer")
)
placeholders: set[str] = set()
for match in Template.pattern.finditer(joined):
if match.group("invalid") is not None:
raise RuntimeContractError(
f"mail.purposes.{purpose} contains an invalid placeholder"
)
name = match.group("named") or match.group("braced")
if name:
placeholders.add(name)
if placeholders != set(required_variables):
raise RuntimeContractError(
f"mail.purposes.{purpose} placeholders do not match required_variables"
)
normalized[purpose] = template
return {"enabled": enabled, "sender": sender, "purposes": normalized}
def _validate_payments(value: Any) -> dict[str, Any]:
payments = _object(
value,
"payments",
{"enabled", "default_adapter", "currency", "local_sandbox", "stripe_test"},
)
enabled = _bool(payments.get("enabled", True), "payments.enabled")
_required(
payments,
"payments",
{"default_adapter", "currency", "local_sandbox", "stripe_test"},
)
if payments["default_adapter"] not in {"local-sandbox", "stripe-test"}:
raise RuntimeContractError("payments.default_adapter is invalid")
currency = _text(payments["currency"], "payments.currency", maximum=3)
if not CURRENCY_RE.fullmatch(currency):
raise RuntimeContractError("payments.currency is invalid")
sandbox = _object(
payments["local_sandbox"], "payments.local_sandbox", {"scenarios"}
)
_required(sandbox, "payments.local_sandbox", {"scenarios"})
scenarios = sandbox["scenarios"]
if not isinstance(scenarios, list) or len(scenarios) < 3:
raise RuntimeContractError(
"payments.local_sandbox.scenarios must contain approval, decline, and retry"
)
seen: set[str] = set()
outcomes: set[str] = set()
normalized_scenarios: list[dict[str, str]] = []
for index, raw_scenario in enumerate(scenarios):
scenario = _object(
raw_scenario,
f"payments.local_sandbox.scenarios[{index}]",
{"id", "outcome", "display_label"},
)
_required(
scenario,
f"payments.local_sandbox.scenarios[{index}]",
{"id", "outcome", "display_label"},
)
scenario_id = _text(
scenario["id"],
f"payments.local_sandbox.scenarios[{index}].id",
maximum=80,
)
if not SCENARIO_ID_RE.fullmatch(scenario_id) or scenario_id in seen:
raise RuntimeContractError("local payment scenario id is invalid")
outcome = scenario["outcome"]
if outcome not in {"approved", "declined", "retryable"}:
raise RuntimeContractError("local payment scenario outcome is invalid")
seen.add(scenario_id)
outcomes.add(outcome)
normalized_scenarios.append(
{
"id": scenario_id,
"outcome": outcome,
"display_label": _text(
scenario["display_label"],
f"payments.local_sandbox.scenarios[{index}].display_label",
maximum=120,
),
}
)
if outcomes != {"approved", "declined", "retryable"}:
raise RuntimeContractError(
"local payment scenarios must cover approved, declined, and retryable"
)
stripe_raw = payments["stripe_test"]
stripe: dict[str, Any] | None
if stripe_raw is None:
stripe = None
else:
stripe = _object(
stripe_raw,
"payments.stripe_test",
{
"public_origin",
"return_path",
"webhook_path",
"max_line_items",
"payment_method_types",
"integration_identifier_prefix",
"secret_key_env",
"webhook_secret_env",
},
)
_required(
stripe,
"payments.stripe_test",
{
"public_origin",
"return_path",
"webhook_path",
"max_line_items",
"secret_key_env",
"webhook_secret_env",
},
)
stripe["public_origin"] = _https_origin(
stripe["public_origin"], "payments.stripe_test.public_origin"
)
stripe["return_path"] = _return_path(
stripe["return_path"], "payments.stripe_test.return_path"
)
stripe["webhook_path"] = _return_path(
stripe["webhook_path"], "payments.stripe_test.webhook_path"
)
if stripe["webhook_path"] == stripe["return_path"]:
raise RuntimeContractError(
"payments.stripe_test webhook and return paths must differ"
)
if (
not isinstance(stripe["max_line_items"], int)
or isinstance(stripe["max_line_items"], bool)
or not 1 <= stripe["max_line_items"] <= 100
):
raise RuntimeContractError(
"payments.stripe_test.max_line_items is invalid"
)
method_types = stripe.get("payment_method_types", ["card", "link"])
if (
not isinstance(method_types, list)
or len(method_types) > 4
or len(method_types) != len(set(method_types))
or not all(item in {"card", "link"} for item in method_types)
):
raise RuntimeContractError(
"payments.stripe_test.payment_method_types is invalid"
)
stripe["payment_method_types"] = method_types
prefix = stripe.get("integration_identifier_prefix")
if prefix is not None:
prefix = _text(
prefix,
"payments.stripe_test.integration_identifier_prefix",
maximum=80,
)
if re.fullmatch(r"[a-z0-9_]+", prefix) is None:
raise RuntimeContractError(
"payments.stripe_test.integration_identifier_prefix is invalid"
)
stripe["integration_identifier_prefix"] = prefix
for key in ("secret_key_env", "webhook_secret_env"):
env_name = _text(stripe[key], f"payments.stripe_test.{key}")
if not ENV_NAME_RE.fullmatch(env_name):
raise RuntimeContractError(f"payments.stripe_test.{key} is invalid")
if payments["default_adapter"] == "stripe-test" and stripe is None:
raise RuntimeContractError("stripe-test adapter requires stripe_test config")
if not enabled and stripe is not None:
raise RuntimeContractError(
"payments.stripe_test must be null when payments are disabled"
)
return {
"enabled": enabled,
"default_adapter": payments["default_adapter"],
"currency": currency,
"local_sandbox": {"scenarios": normalized_scenarios},
"stripe_test": stripe,
}
def _validate_deployment(value: Any) -> dict[str, Any]:
deployment = _object(value, "deployment", {"profiles"})
_required(deployment, "deployment", {"profiles"})
profiles = deployment["profiles"]
if not isinstance(profiles, dict):
raise RuntimeContractError("deployment.profiles must be an object")
required_profiles = {"offline-harbor", "cloudflare-review", "docker-volume"}
if set(profiles) != required_profiles:
raise RuntimeContractError(
"deployment.profiles must define offline-harbor, cloudflare-review, and docker-volume"
)
expected = {
"offline-harbor": ("persistent", "local-outbox"),
"cloudflare-review": ("ephemeral-reset", "redis-resend"),
"docker-volume": ("persistent-volume", "effects-gateway"),
}
normalized: dict[str, Any] = {}
for name, raw_profile in profiles.items():
profile = _object(
raw_profile,
f"deployment.profiles.{name}",
{"persistence", "mail_adapter", "payment_adapter"},
)
_required(
profile,
f"deployment.profiles.{name}",
{"persistence", "mail_adapter", "payment_adapter"},
)
persistence, mail_adapter = expected[name]
if profile["persistence"] != persistence:
raise RuntimeContractError(
f"deployment.profiles.{name}.persistence must be {persistence}"
)
if profile["mail_adapter"] != mail_adapter:
raise RuntimeContractError(
f"deployment.profiles.{name}.mail_adapter must be {mail_adapter}"
)
if profile["payment_adapter"] not in {"local-sandbox", "stripe-test"}:
raise RuntimeContractError(
f"deployment.profiles.{name}.payment_adapter is invalid"
)
normalized[name] = dict(profile)
return {"profiles": normalized}
def validate_runtime(value: Any, *, source_path: Path | None = None) -> RuntimeConfig:
root = _object(
value,
"runtime",
{
"schema_version",
"site",
"database",
"session",
"mail",
"payments",
"deployment",
},
)
_required(
root,
"runtime",
{
"schema_version",
"site",
"database",
"session",
"mail",
"payments",
"deployment",
},
)
if root["schema_version"] != RUNTIME_SCHEMA_VERSION:
raise RuntimeContractError("unsupported runtime schema_version")
site = _object(root["site"], "site", {"id", "label", "public_origin"})
_required(site, "site", {"id", "label", "public_origin"})
site_id = _text(site["id"], "site.id", maximum=63)
if not SITE_ID_RE.fullmatch(site_id):
raise RuntimeContractError("site.id is invalid")
site_label = _text(site["label"], "site.label", maximum=120)
public_origin = _https_origin(site["public_origin"], "site.public_origin")
database = _object(
root["database"],
"database",
{
"engine",
"data_dir",
"filename",
"volume_identity",
"migration_hook",
"seed_hook",
"legacy_unbound_migration",
},
)
_required(
database,
"database",
{
"engine",
"data_dir",
"filename",
"migration_hook",
"seed_hook",
"legacy_unbound_migration",
},
)
if database["engine"] != "sqlite":
raise RuntimeContractError("database.engine must be sqlite")
data_dir = _safe_relative_path(database["data_dir"], "database.data_dir")
filename = _safe_relative_path(
database["filename"], "database.filename", basename=True
)
if not filename.endswith((".sqlite", ".sqlite3", ".db")):
raise RuntimeContractError("database.filename must be a SQLite filename")
volume_identity = _text(
database.get("volume_identity", f"websitebench-{site_id}-data"),
"database.volume_identity",
maximum=90,
)
if not VOLUME_IDENTITY_RE.fullmatch(volume_identity):
raise RuntimeContractError("database.volume_identity is invalid")
if volume_identity != f"websitebench-{site_id}-data":
raise RuntimeContractError(
"database.volume_identity must be derived from site.id"
)
for hook_name in ("migration_hook", "seed_hook"):
hook = database[hook_name]
if hook is not None:
text = _text(hook, f"database.{hook_name}", maximum=200)
if not re.fullmatch(
r"[A-Za-z_][A-Za-z0-9_.]*:[A-Za-z_][A-Za-z0-9_]*", text
):
raise RuntimeContractError(f"database.{hook_name} is invalid")
legacy_unbound = _bool(
database["legacy_unbound_migration"], "database.legacy_unbound_migration"
)
session = _object(
root["session"],
"session",
{"host_only", "secure", "http_only", "same_site"},
)
_required(
session,
"session",
{"host_only", "secure", "http_only", "same_site"},
)
_bool(session["host_only"], "session.host_only", True)
_bool(session["secure"], "session.secure", True)
_bool(session["http_only"], "session.http_only", True)
if session["same_site"] not in {"Lax", "Strict"}:
raise RuntimeContractError("session.same_site must be Lax or Strict")
mail = _validate_mail(root["mail"])
payments = _validate_payments(root["payments"])
if (
payments["stripe_test"] is not None
and payments["stripe_test"]["public_origin"] != public_origin
):
raise RuntimeContractError(
"payments.stripe_test.public_origin must match site.public_origin"
)
deployment = _validate_deployment(root["deployment"])
if any(
profile["payment_adapter"] == "stripe-test"
for profile in deployment["profiles"].values()
) and payments["stripe_test"] is None:
raise RuntimeContractError(
"a stripe-test deployment profile requires payments.stripe_test"
)
normalized = {
"schema_version": RUNTIME_SCHEMA_VERSION,
"site": {
"id": site_id,
"label": site_label,
"public_origin": public_origin,
},
"database": {
"engine": "sqlite",
"data_dir": data_dir,
"filename": filename,
"volume_identity": volume_identity,
"migration_hook": database["migration_hook"],
"seed_hook": database["seed_hook"],
"legacy_unbound_migration": legacy_unbound,
},
"session": dict(session),
"mail": mail,
"payments": payments,
"deployment": deployment,
}
return RuntimeConfig(
source_path=source_path,
site_id=site_id,
site_label=site_label,
public_origin=public_origin,
data_dir=data_dir,
database_filename=filename,
volume_identity=volume_identity,
migration_hook=database["migration_hook"],
seed_hook=database["seed_hook"],
legacy_unbound_migration=legacy_unbound,
session=MappingProxyType(dict(session)),
mail=MappingProxyType(mail),
payments=MappingProxyType(payments),
deployment=MappingProxyType(deployment),
raw=MappingProxyType(normalized),
)
def load_runtime(value: Path | str | Mapping[str, Any]) -> RuntimeConfig:
if isinstance(value, Mapping):
return validate_runtime(dict(value))
path = Path(value).absolute()
if not path.is_file() or path.is_symlink():
raise RuntimeContractError("runtime contract must be a regular file")
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise RuntimeContractError(f"cannot read runtime contract: {exc}") from exc
return validate_runtime(raw, source_path=path.resolve())
|