File size: 7,879 Bytes
187ef74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generated, site-bound backend integration seam."""

from __future__ import annotations

import importlib
import json
import os
import secrets
import sqlite3
import stat
from pathlib import Path
from typing import Any, Callable

from websitebench.local_clone_auth import (
    MAIL_LOCAL_ONLY,
    MAIL_SMTP_PENDING,
    LocalAuthStore,
)
from websitebench.site_backend import SiteBackend, load_runtime
DEFAULT_RUNTIME_PATH = (
    Path(__file__).resolve().parents[2] / "backend" / "runtime.json"
)
DEFAULT_DEPLOYMENT_PROFILE = "offline-harbor"
_AUTH_MAIL_WORKER_TOKEN = secrets.token_urlsafe(32)


def auth_mail_worker_token() -> str:
    """Return process-local mail-worker authority; never persist or expose it."""

    return _AUTH_MAIL_WORKER_TOKEN


def auth_mail_delivery_enabled(backend: SiteBackend) -> bool:
    """Whether the selected runtime profile delegates mail to the gateway."""

    profile = getattr(backend, "deployment_profile", {})
    return profile.get("mail_adapter") in {"redis-resend", "effects-gateway"}


def resolve_runtime_path() -> Path:
    """Resolve the one process-wide Eventbrite runtime contract path."""

    return Path(
        os.environ.get(
            "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
            str(DEFAULT_RUNTIME_PATH),
        )
    ).absolute()


def load_site_runtime(runtime_path: Path | None = None):
    """Load the same runtime contract used by ``open_site_services``."""

    return load_runtime((runtime_path or resolve_runtime_path()).absolute())


def resolve_deployment_profile(
    runtime: Any,
    environment: dict[str, str] | None = None,
) -> tuple[str, dict[str, Any]]:
    """Select the one runtime-declared profile used by this process."""

    source = os.environ if environment is None else environment
    profile_name = source.get(
        "WEBSITEBENCH_BACKEND_PROFILE", DEFAULT_DEPLOYMENT_PROFILE
    ).strip()
    if not profile_name:
        profile_name = DEFAULT_DEPLOYMENT_PROFILE
    profile = runtime.deployment["profiles"].get(profile_name)
    if profile is None:
        raise RuntimeError(
            "Eventbrite backend profile is not declared by the runtime contract"
        )
    return profile_name, dict(profile)


def _secure_sqlite_files(database: Path) -> None:
    """Keep the site database and transient SQLite sidecars owner-only."""
    for candidate in (
        database,
        Path(f"{database}-wal"),
        Path(f"{database}-shm"),
    ):
        flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
        try:
            descriptor = os.open(candidate, flags)
        except FileNotFoundError:
            continue
        try:
            details = os.fstat(descriptor)
            if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid():
                raise RuntimeError(
                    "Eventbrite SQLite storage must be regular and owned by "
                    "the runtime user"
                )
            os.fchmod(descriptor, 0o600)
        finally:
            os.close(descriptor)


def _declared_hook(
    declaration: str | None,
) -> Callable[[sqlite3.Connection], None] | None:
    if declaration is None:
        return None
    module_name, function_name = declaration.split(":", 1)
    module = importlib.import_module(module_name)
    hook: Any = getattr(module, function_name, None)
    if not callable(hook):
        raise RuntimeError(f"declared backend hook is not callable: {declaration}")
    actual = f"{hook.__module__}:{hook.__name__}"
    if actual != declaration:
        raise RuntimeError(
            f"declared backend hook resolved as {actual!r}, expected {declaration!r}"
        )
    return hook


def open_site_services(
    *,
    mail_mode: str | None = None,
    mail_worker_token: str | None = None,
    database_path: Path | None = None,
    auth_now: Callable[[], int] | None = None,
    runtime_path: Path | None = None,
    expected_runtime: Any | None = None,
) -> tuple[SiteBackend, LocalAuthStore]:
    """Open one bound database; never omit the site id for permanent auth."""

    runtime_path = (runtime_path or resolve_runtime_path()).absolute()
    runtime = load_site_runtime(runtime_path)
    if expected_runtime is not None and dict(runtime.raw) != dict(
        expected_runtime.raw
    ):
        raise RuntimeError("Eventbrite backend runtime contract changed")
    profile_name, profile = resolve_deployment_profile(runtime)
    mail_adapter = profile["mail_adapter"]
    if mail_adapter not in {"local-outbox", "redis-resend", "effects-gateway"}:
        raise RuntimeError(
            "Eventbrite backend profile has an unsupported mail adapter"
        )
    if profile["payment_adapter"] != "local-sandbox":
        raise RuntimeError(
            "Eventbrite backend profile must use the local-sandbox payment adapter"
        )
    remote_mail = mail_adapter in {"redis-resend", "effects-gateway"}
    expected_mail_mode = MAIL_SMTP_PENDING if remote_mail else MAIL_LOCAL_ONLY
    selected_mail_mode = mail_mode or expected_mail_mode
    if selected_mail_mode != expected_mail_mode:
        raise RuntimeError(
            "Eventbrite auth mail mode differs from the deployment profile"
        )
    selected_worker_token = (
        mail_worker_token or _AUTH_MAIL_WORKER_TOKEN if remote_mail else None
    )
    migration_hook = _declared_hook(runtime.migration_hook)
    seed_hook = _declared_hook(runtime.seed_hook)
    deployed_database = os.environ.get("WEBSITEBENCH_SITE_BACKEND_DATABASE")
    selected_database = (
        Path(deployed_database).resolve()
        if deployed_database is not None
        else database_path.resolve()
        if database_path is not None
        else (runtime.site_root / runtime.data_dir / runtime.database_filename).resolve()
        if runtime.site_root is not None
        else None
    )
    if selected_database is None:
        raise RuntimeError("Eventbrite backend database path is unresolved")
    if selected_database.name != runtime.database_filename:
        raise RuntimeError(
            "deployed database filename does not match runtime contract"
        )
    runtime_database = (
        (runtime.site_root / runtime.data_dir / runtime.database_filename).resolve()
        if runtime.site_root is not None
        else None
    )
    if selected_database == runtime_database:
        backend = SiteBackend.open(
            runtime_path,
            migration_hook=migration_hook,
            seed_hook=seed_hook,
        )
    else:
        # A test/container database is still governed by the exact committed
        # contract, but loading that contract as data intentionally leaves it
        # unbound from the repository's default ``data/`` directory.
        backend = SiteBackend.open(
            json.loads(runtime_path.read_text(encoding="utf-8")),
            data_root=selected_database.parent,
            migration_hook=migration_hook,
            seed_hook=seed_hook,
        )
    if backend.lifecycle.database_path != selected_database:
        raise RuntimeError(
            "deployed database path does not match backend preflight"
        )
    if dict(backend.config.raw) != dict(runtime.raw):
        raise RuntimeError("Eventbrite backend runtime contract diverged")
    backend.lifecycle.initialize()
    _secure_sqlite_files(backend.lifecycle.database_path)
    auth_options: dict[str, Any] = {
        "site_id": backend.config.site_id,
        "mail_mode": selected_mail_mode,
        "mail_worker_token": selected_worker_token,
    }
    if auth_now is not None:
        auth_options["now"] = auth_now
    auth = LocalAuthStore(backend.lifecycle.database_path, **auth_options)
    auth.ensure_schema()
    _secure_sqlite_files(backend.lifecycle.database_path)
    backend.deployment_profile_name = profile_name
    backend.deployment_profile = profile
    return backend, auth