AgPerry commited on
Commit
3c4befe
·
verified ·
1 Parent(s): a976fe6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/brooklinen/environment/candidate-abi/websitebench/__init__.py +1 -0
  2. tasks/brooklinen/environment/candidate-abi/websitebench/harbor/__init__.py +1 -0
  3. tasks/brooklinen/environment/candidate-abi/websitebench/harbor/candidate_preflight.py +179 -0
  4. tasks/brooklinen/environment/candidate-abi/websitebench/harbor/compiler.py +1128 -0
  5. tasks/brooklinen/environment/candidate-abi/websitebench/harbor/sandbox.py +841 -0
  6. tasks/brooklinen/environment/reference/clone/frontend/templates/_card.html +24 -0
  7. tasks/brooklinen/environment/reference/clone/frontend/templates/account.html +37 -0
  8. tasks/brooklinen/environment/reference/clone/frontend/templates/base.html +110 -0
  9. tasks/brooklinen/environment/reference/clone/frontend/templates/cart.html +51 -0
  10. tasks/brooklinen/environment/reference/clone/frontend/templates/checkout.html +20 -0
  11. tasks/brooklinen/environment/reference/clone/frontend/templates/collection.html +50 -0
  12. tasks/brooklinen/environment/reference/clone/frontend/templates/content.html +9 -0
  13. tasks/brooklinen/environment/reference/clone/frontend/templates/home.html +113 -0
  14. tasks/brooklinen/environment/reference/clone/frontend/templates/landing.html +79 -0
  15. tasks/brooklinen/environment/reference/clone/frontend/templates/login.html +19 -0
  16. tasks/brooklinen/environment/reference/clone/frontend/templates/notfound.html +9 -0
  17. tasks/brooklinen/environment/reference/clone/frontend/templates/order.html +14 -0
  18. tasks/brooklinen/environment/reference/clone/frontend/templates/outbox.html +10 -0
  19. tasks/brooklinen/environment/reference/clone/frontend/templates/product.html +64 -0
  20. tasks/brooklinen/environment/reference/clone/frontend/templates/register.html +26 -0
  21. tasks/brooklinen/environment/reference/clone/frontend/templates/search.html +14 -0
  22. tasks/brooklinen/environment/reference/clone/static/assets/fonts/ToledoSerial-Bold.otf +0 -0
  23. tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextBold.woff2 +0 -0
  24. tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextRegular.woff2 +0 -0
  25. tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextWeb-Italic--360967_8_0.woff2 +0 -0
  26. tasks/brooklinen/environment/reference/clone/static/assets/fonts/wf_BrandonTextWeb-Medium--360967_B_0.woff2 +0 -0
  27. tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9149_x_PDP_WO_f6573af1-b775-4727-a79a-783a72bdeb9d__600x.jpg +3 -0
  28. tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9170_x_PDP_WO_72702b5e-b89e-427e-bde0-cd7d52897d50__600x.jpg +3 -0
  29. tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9199_x_PDP_WO_44efe1fe-6aa4-4e29-9d64-2c9c4799640b__600x.jpg +3 -0
  30. tasks/brooklinen/environment/reference/clone/static/assets/img/1_BKL_20_AltDownTopper_UB_2__400x.jpg +3 -0
  31. tasks/brooklinen/environment/reference/clone/static/assets/img/1_BKL_20_PillowProtector_UB_2__400x.jpg +3 -0
  32. tasks/brooklinen/environment/reference/clone/static/assets/img/250723_WashedClassicOverhead7114x_PDP_WO_2f1a33bd-6c4a-4912-a6aa-03864ea5d29d__600x.jpg +3 -0
  33. tasks/brooklinen/environment/reference/clone/static/assets/img/250723_WashedClassicOverhead7372x_PDP_WO__600x.jpg +3 -0
  34. tasks/brooklinen/environment/reference/clone/static/assets/img/BK0654_1__150x.jpg +3 -0
  35. tasks/brooklinen/environment/reference/clone/static/assets/img/BK1064_1__600x.jpg +3 -0
  36. tasks/brooklinen/environment/reference/clone/static/assets/img/BK1D2F_1__600x.jpg +3 -0
  37. tasks/brooklinen/environment/reference/clone/static/assets/img/BK2D69_1__150x.jpg +3 -0
  38. tasks/brooklinen/environment/reference/clone/static/assets/img/BK4478_1__150x.jpg +3 -0
  39. tasks/brooklinen/environment/reference/clone/static/assets/img/BK6EF5_1__600x.jpg +3 -0
  40. tasks/brooklinen/environment/reference/clone/static/assets/img/BK73A3_1__600x.jpg +3 -0
  41. tasks/brooklinen/environment/reference/clone/static/assets/img/BK7885_1__150x.jpg +3 -0
  42. tasks/brooklinen/environment/reference/clone/static/assets/img/BK8506_1__150x.jpg +3 -0
  43. tasks/brooklinen/environment/reference/clone/static/assets/img/BK9711_1_965df1b0-454d-48dc-812e-5024396583f6__150x.jpg +3 -0
  44. tasks/brooklinen/environment/reference/clone/static/assets/img/BKA027_1__150x.jpg +3 -0
  45. tasks/brooklinen/environment/reference/clone/static/assets/img/BKAD07_1__1000x.jpg +3 -0
  46. tasks/brooklinen/environment/reference/clone/static/assets/img/BKAD07_1__400x.jpg +3 -0
  47. tasks/brooklinen/environment/reference/clone/static/assets/img/BKAEA8_1__150x.jpg +3 -0
  48. tasks/brooklinen/environment/reference/clone/static/assets/img/BKB424_1__400x.jpg +3 -0
  49. tasks/brooklinen/environment/reference/clone/static/assets/img/BKD0CB_1__1000x.jpg +3 -0
  50. tasks/brooklinen/environment/reference/clone/static/assets/img/BKD0CB_1__150x.jpg +3 -0
tasks/brooklinen/environment/candidate-abi/websitebench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public WebsiteBench candidate ABI tooling."""
tasks/brooklinen/environment/candidate-abi/websitebench/harbor/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Public Harbor candidate ABI tooling."""
tasks/brooklinen/environment/candidate-abi/websitebench/harbor/candidate_preflight.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-visible preflight for the public Harbor candidate runtime ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import socket
8
+ import sys
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Sequence
12
+
13
+ from .compiler import (
14
+ CompilerSandboxError,
15
+ RuntimeInfrastructureError,
16
+ compile_candidate,
17
+ validate_runtime_lifecycle,
18
+ )
19
+
20
+
21
+ FORBIDDEN_PRIVATE_ROOT = b"/app/repo"
22
+ NONPORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/python3"
23
+ PORTABLE_PYTHON_SHEBANG = b"#!/usr/bin/env python3"
24
+
25
+
26
+ def _first_line(path: Path) -> bytes:
27
+ with path.open("rb") as handle:
28
+ return handle.readline(4097).rstrip(b"\r\n")
29
+
30
+
31
+ def _contains(path: Path, needle: bytes) -> bool:
32
+ overlap = max(0, len(needle) - 1)
33
+ previous = b""
34
+ with path.open("rb") as handle:
35
+ while chunk := handle.read(1024 * 1024):
36
+ value = previous + chunk
37
+ if needle in value:
38
+ return True
39
+ previous = value[-overlap:] if overlap else b""
40
+ return False
41
+
42
+
43
+ def validate_portable_candidate_paths(
44
+ compile_script: Path, executable: Path | None = None
45
+ ) -> None:
46
+ """Reject paths that work in the Agent checkout but not the private build."""
47
+
48
+ if _contains(compile_script, FORBIDDEN_PRIVATE_ROOT):
49
+ raise CompilerSandboxError(
50
+ "compile.sh hard-codes /app/repo; the verifier relocates the candidate "
51
+ "to a private build root. Use paths relative to the current directory "
52
+ "or $WEBSITEBENCH_BUILD_ROOT."
53
+ )
54
+ if _first_line(compile_script) == NONPORTABLE_PYTHON_SHEBANG:
55
+ raise CompilerSandboxError(
56
+ "compile.sh uses the non-portable #!/usr/bin/python3 shebang; use "
57
+ "#!/usr/bin/env python3."
58
+ )
59
+ if executable is None:
60
+ return
61
+ if _first_line(executable) == NONPORTABLE_PYTHON_SHEBANG:
62
+ raise CompilerSandboxError(
63
+ "executable uses the non-portable #!/usr/bin/python3 shebang; use "
64
+ "#!/usr/bin/env python3."
65
+ )
66
+ if _contains(executable, FORBIDDEN_PRIVATE_ROOT):
67
+ raise CompilerSandboxError(
68
+ "executable contains /app/repo; runtime files live in the private "
69
+ "build root. Resolve resources relative to executable, not /app/repo."
70
+ )
71
+
72
+
73
+ def _free_port() -> int:
74
+ with socket.socket() as probe:
75
+ probe.bind(("127.0.0.1", 0))
76
+ return int(probe.getsockname()[1])
77
+
78
+
79
+ def _build_log(private_root: Path) -> str:
80
+ path = private_root / "build.log"
81
+ try:
82
+ value = path.read_text(encoding="utf-8", errors="replace")
83
+ except OSError:
84
+ return ""
85
+ return value[-65536:]
86
+
87
+
88
+ def run_preflight(
89
+ candidate_root: Path,
90
+ *,
91
+ timeout: float = 300.0,
92
+ seed: int = 0,
93
+ timezone: str = "UTC",
94
+ ) -> dict[str, object]:
95
+ candidate = candidate_root.resolve(strict=True)
96
+ compile_script = candidate / "compile.sh"
97
+ if not compile_script.is_file():
98
+ raise CompilerSandboxError("candidate root does not contain compile.sh")
99
+ validate_portable_candidate_paths(compile_script)
100
+ with tempfile.TemporaryDirectory(prefix="websitebench-candidate-preflight-") as raw:
101
+ working_root = Path(raw)
102
+ private_root = working_root / "compiler"
103
+ try:
104
+ artifact = compile_candidate(
105
+ candidate,
106
+ private_root,
107
+ timeout=timeout,
108
+ seed=seed,
109
+ timezone=timezone,
110
+ )
111
+ except CompilerSandboxError as exc:
112
+ log = _build_log(private_root)
113
+ if log:
114
+ raise CompilerSandboxError(f"{exc}\ncompiler output:\n{log}") from exc
115
+ raise
116
+ validate_portable_candidate_paths(
117
+ artifact.build_root / "compile.sh", artifact.executable
118
+ )
119
+ lifecycle = validate_runtime_lifecycle(
120
+ artifact,
121
+ port=_free_port(),
122
+ seed=seed,
123
+ working_root=working_root / "runtime-preflight",
124
+ worker_access_roots=(working_root,),
125
+ timezone=timezone,
126
+ )
127
+ if lifecycle.get("valid") is not True:
128
+ failed = sorted(
129
+ key
130
+ for key, value in lifecycle.items()
131
+ if key not in {"deployment_abi", "tree_sha256", "valid"}
132
+ and value is not True
133
+ )
134
+ raise CompilerSandboxError(
135
+ "candidate runtime ABI lifecycle failed: " + ",".join(failed)
136
+ )
137
+ return {
138
+ "schema": "websitebench.harbor.candidate-preflight",
139
+ "status": "valid",
140
+ "candidate_root": str(candidate),
141
+ "tree_sha256": artifact.tree_sha256,
142
+ "lifecycle": lifecycle,
143
+ }
144
+
145
+
146
+ def _parser() -> argparse.ArgumentParser:
147
+ parser = argparse.ArgumentParser(
148
+ description="Check a candidate with the formal private compile/runtime ABI."
149
+ )
150
+ parser.add_argument("candidate_root", nargs="?", type=Path, default=Path.cwd())
151
+ parser.add_argument("--timeout", type=float, default=300.0)
152
+ parser.add_argument("--seed", type=int, default=0)
153
+ parser.add_argument("--timezone", default="UTC")
154
+ return parser
155
+
156
+
157
+ def main(arguments: Sequence[str] | None = None) -> int:
158
+ values = _parser().parse_args(arguments)
159
+ try:
160
+ report = run_preflight(
161
+ values.candidate_root,
162
+ timeout=values.timeout,
163
+ seed=values.seed,
164
+ timezone=values.timezone,
165
+ )
166
+ except (
167
+ CompilerSandboxError,
168
+ RuntimeInfrastructureError,
169
+ OSError,
170
+ ValueError,
171
+ ) as exc:
172
+ print(f"candidate ABI preflight failed: {exc}", file=sys.stderr)
173
+ return 2
174
+ print(json.dumps(report, indent=2, sort_keys=True))
175
+ return 0
176
+
177
+
178
+ if __name__ == "__main__":
179
+ raise SystemExit(main())
tasks/brooklinen/environment/candidate-abi/websitebench/harbor/compiler.py ADDED
@@ -0,0 +1,1128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Quarantined compiler and runtime for the Harbor compile-executable ABI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import errno
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import shutil
11
+ import signal
12
+ import stat
13
+ import subprocess
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Iterable, Mapping, Sequence
20
+
21
+ try: # pragma: no cover - unavailable on Windows authoring hosts
22
+ import resource
23
+ except ImportError: # pragma: no cover
24
+ resource = None # type: ignore[assignment]
25
+
26
+ from . import sandbox
27
+
28
+
29
+ DEPLOYMENT_ABI = "websitebench.harbor.compile-executable"
30
+ COMPILE_ENTRYPOINT = "compile.sh"
31
+ EXECUTABLE_ENTRYPOINT = "executable"
32
+ HEALTH_PATH = "/healthz"
33
+ # The contract moved to /healthz (ADR-0010) because every reference site and
34
+ # every manifest already served that path, while nothing ever implemented the
35
+ # benchmark-private one. Candidates built against the old instruction text keep
36
+ # working: probing falls back to these.
37
+ LEGACY_HEALTH_PATHS = ("/__websitebench/health",)
38
+ HEALTH_PATHS = (HEALTH_PATH, *LEGACY_HEALTH_PATHS)
39
+ HEALTH_BODY = {"status": "ok"}
40
+ RUNTIME_PROCESS_MODEL = {
41
+ "kind": "single-process",
42
+ "process_fork": False,
43
+ "threads": True,
44
+ "launcher": "direct-exec-or-shell-builtins-only",
45
+ }
46
+ DEFAULT_COMPILE_TIMEOUT = 900.0
47
+ MAX_LOG_BYTES = 256 * 1024 * 1024
48
+ WORKER_OS_UID = 10001
49
+ WORKER_OS_GID = 10001
50
+ _RUNTIME_PRIVATE_DIRECTORIES = (
51
+ "home",
52
+ "tmp",
53
+ "xdg-cache",
54
+ "xdg-config",
55
+ "xdg-data",
56
+ )
57
+ CANDIDATE_MAIL_ENVIRONMENT = frozenset(
58
+ {
59
+ "WEBSITEBENCH_MAIL_API_URL",
60
+ "WEBSITEBENCH_MAIL_API_TOKEN",
61
+ "WEBSITEBENCH_MAIL_FROM",
62
+ "WEBSITEBENCH_SMTP_HOST",
63
+ "WEBSITEBENCH_SMTP_PORT",
64
+ "WEBSITEBENCH_SMTP_FROM",
65
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_URL",
66
+ "WEBSITEBENCH_MAILBOX_BOOTSTRAP_TOKEN",
67
+ }
68
+ )
69
+ CANDIDATE_EVALUATOR_ENVIRONMENT = frozenset(
70
+ {
71
+ "WEBSITEBENCH_VERIFIER_MODE",
72
+ "WEBSITEBENCH_VERIFIER_ALEX_SECRET",
73
+ "WEBSITEBENCH_VERIFIER_JORDAN_SECRET",
74
+ "WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET",
75
+ "WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET",
76
+ }
77
+ )
78
+
79
+
80
+ class CompilerSandboxError(RuntimeError):
81
+ """The candidate artifact, compiler, or compiled runtime broke the ABI."""
82
+
83
+
84
+ class RuntimeInfrastructureError(RuntimeError):
85
+ """The trusted runtime supervisor could not establish its worker boundary."""
86
+
87
+
88
+ def _runtime_worker_credentials() -> tuple[int, int] | None:
89
+ """Return the fixed worker identity only for a privileged supervisor."""
90
+
91
+ if os.geteuid() == 0:
92
+ return WORKER_OS_UID, WORKER_OS_GID
93
+ return None
94
+
95
+
96
+ def _worker_execute_bit(metadata: os.stat_result, uid: int, gid: int) -> int:
97
+ if metadata.st_uid == uid:
98
+ return stat.S_IXUSR
99
+ if metadata.st_gid == gid:
100
+ return stat.S_IXGRP
101
+ return stat.S_IXOTH
102
+
103
+
104
+ def _worker_access_root(path: Path, roots: Sequence[Path]) -> Path:
105
+ matches = [root for root in roots if path == root or root in path.parents]
106
+ if not matches:
107
+ raise OSError(
108
+ errno.EPERM,
109
+ f"worker path is outside caller-declared access roots: {path}",
110
+ )
111
+ return max(matches, key=lambda root: len(root.parts))
112
+
113
+
114
+ def _make_worker_ancestors_traversable(
115
+ path: Path,
116
+ uid: int,
117
+ gid: int,
118
+ *,
119
+ access_root: Path,
120
+ ) -> None:
121
+ """Grant traverse only within one exact caller-declared task root."""
122
+
123
+ for boundary_parent in access_root.parents:
124
+ metadata = boundary_parent.stat()
125
+ if not stat.S_ISDIR(metadata.st_mode) or not (
126
+ stat.S_IMODE(metadata.st_mode)
127
+ & _worker_execute_bit(metadata, uid, gid)
128
+ ):
129
+ raise OSError(
130
+ errno.EACCES,
131
+ f"worker access-root boundary is not traversable: {boundary_parent}",
132
+ )
133
+
134
+ ancestors = [path, *path.parents]
135
+ try:
136
+ boundary_index = ancestors.index(access_root)
137
+ except ValueError as exc: # guarded by _worker_access_root
138
+ raise OSError(errno.EPERM, "worker access-root containment changed") from exc
139
+ for ancestor in ancestors[: boundary_index + 1]:
140
+ metadata = ancestor.stat()
141
+ if not stat.S_ISDIR(metadata.st_mode):
142
+ raise OSError(errno.ENOTDIR, f"worker ancestor is not a directory: {ancestor}")
143
+ mode = stat.S_IMODE(metadata.st_mode)
144
+ execute_bit = _worker_execute_bit(metadata, uid, gid)
145
+ if not mode & execute_bit:
146
+ ancestor.chmod(mode | execute_bit)
147
+
148
+
149
+ def _prepare_runtime_directories(
150
+ build: Path,
151
+ data: Path,
152
+ credentials: tuple[int, int] | None,
153
+ *,
154
+ worker_access_roots: Sequence[Path],
155
+ ) -> None:
156
+ """Create private runtime state and make it usable by the worker identity."""
157
+
158
+ data.mkdir(parents=True, exist_ok=True, mode=0o700)
159
+ private_directories = [data]
160
+ for name in _RUNTIME_PRIVATE_DIRECTORIES:
161
+ directory = data / name
162
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
163
+ private_directories.append(directory)
164
+
165
+ for directory in private_directories:
166
+ metadata = directory.lstat()
167
+ if not stat.S_ISDIR(metadata.st_mode):
168
+ raise OSError(
169
+ errno.ENOTDIR,
170
+ f"runtime private path is not a directory: {directory}",
171
+ )
172
+
173
+ if credentials is not None:
174
+ uid, gid = credentials
175
+ roots: list[Path] = []
176
+ for raw_root in worker_access_roots:
177
+ absolute = Path(raw_root).absolute()
178
+ root = absolute.resolve(strict=True)
179
+ metadata = absolute.lstat()
180
+ if (
181
+ root == Path(root.anchor)
182
+ or root != absolute
183
+ or not stat.S_ISDIR(metadata.st_mode)
184
+ ):
185
+ raise OSError(errno.EPERM, f"invalid worker access root: {raw_root}")
186
+ if root not in roots:
187
+ roots.append(root)
188
+ if not roots:
189
+ raise OSError(errno.EPERM, "worker access roots were not declared")
190
+ for directory in private_directories:
191
+ os.chown(directory, uid, gid, follow_symlinks=False)
192
+ for target in (build, data):
193
+ access_root = _worker_access_root(target, roots)
194
+ _make_worker_ancestors_traversable(
195
+ target,
196
+ uid,
197
+ gid,
198
+ access_root=access_root,
199
+ )
200
+
201
+ for directory in private_directories:
202
+ directory.chmod(0o700)
203
+
204
+
205
+ def _proc_status_identity(path: Path) -> tuple[tuple[int, ...], tuple[int, ...], int]:
206
+ """Read real/effective/saved/fs IDs and PPid from a proc status file."""
207
+
208
+ fields: dict[str, tuple[int, ...]] = {}
209
+ try:
210
+ for line in path.read_text(encoding="ascii").splitlines():
211
+ name, separator, value = line.partition(":")
212
+ if separator and name in {"Uid", "Gid", "PPid"}:
213
+ fields[name] = tuple(int(item) for item in value.split())
214
+ except (OSError, UnicodeError, ValueError) as exc:
215
+ raise OSError(errno.EIO, f"process identity is unreadable: {path}") from exc
216
+ if len(fields.get("Uid", ())) != 4 or len(fields.get("Gid", ())) != 4:
217
+ raise OSError(errno.EIO, f"process identity is incomplete: {path}")
218
+ if len(fields.get("PPid", ())) != 1:
219
+ raise OSError(errno.EIO, f"process parent identity is incomplete: {path}")
220
+ return fields["Uid"], fields["Gid"], fields["PPid"][0]
221
+
222
+
223
+ @dataclass(frozen=True)
224
+ class CompiledArtifact:
225
+ source_root: Path
226
+ build_root: Path
227
+ executable: Path
228
+ tree_sha256: str
229
+ build_log: Path
230
+
231
+
232
+ def _safe_name(name: str) -> bool:
233
+ return (
234
+ bool(name)
235
+ and name not in {".", ".."}
236
+ and "/" not in name
237
+ and "\x00" not in name
238
+ )
239
+
240
+
241
+ def _tree_entries(root: Path) -> Iterable[tuple[Path, os.stat_result]]:
242
+ """Walk with lstat only; never follow candidate-authored links."""
243
+
244
+ stack = [root]
245
+ while stack:
246
+ directory = stack.pop()
247
+ with os.scandir(directory) as iterator:
248
+ entries = sorted(iterator, key=lambda item: os.fsencode(item.name))
249
+ subdirectories: list[Path] = []
250
+ for entry in entries:
251
+ if not _safe_name(entry.name):
252
+ raise CompilerSandboxError(f"unsafe artifact name: {entry.name!r}")
253
+ path = Path(entry.path)
254
+ metadata = entry.stat(follow_symlinks=False)
255
+ yield path, metadata
256
+ if stat.S_ISDIR(metadata.st_mode):
257
+ subdirectories.append(path)
258
+ stack.extend(reversed(subdirectories))
259
+
260
+
261
+ def validate_artifact_tree(root: Path | str) -> list[Path]:
262
+ """Reject links, special files, multiple links, and paths outside ``root``."""
263
+
264
+ resolved = Path(root).resolve(strict=True)
265
+ root_stat = resolved.lstat()
266
+ if not stat.S_ISDIR(root_stat.st_mode):
267
+ raise CompilerSandboxError("candidate artifact root must be a directory")
268
+ files: list[Path] = []
269
+ for path, metadata in _tree_entries(resolved):
270
+ try:
271
+ relative = path.relative_to(resolved)
272
+ except ValueError as exc: # defensive: scandir paths must remain below root
273
+ raise CompilerSandboxError(f"artifact path escapes root: {path}") from exc
274
+ if not relative.parts or any(
275
+ part in {"", ".", ".."} for part in relative.parts
276
+ ):
277
+ raise CompilerSandboxError(f"unsafe artifact path: {relative}")
278
+ if stat.S_ISLNK(metadata.st_mode):
279
+ raise CompilerSandboxError(f"symbolic links are forbidden: {relative}")
280
+ if stat.S_ISREG(metadata.st_mode):
281
+ if metadata.st_nlink != 1:
282
+ raise CompilerSandboxError(
283
+ f"hard-linked files are forbidden: {relative}"
284
+ )
285
+ files.append(path)
286
+ elif not stat.S_ISDIR(metadata.st_mode):
287
+ raise CompilerSandboxError(f"special files are forbidden: {relative}")
288
+ return files
289
+
290
+
291
+ def quarantine_artifact(source: Path | str, destination: Path | str) -> Path:
292
+ """Copy `/app/repo` into a fresh private build root without link semantics."""
293
+
294
+ source_root = Path(source).resolve(strict=True)
295
+ destination_root = Path(destination).resolve()
296
+ validate_artifact_tree(source_root)
297
+ if destination_root.exists():
298
+ raise FileExistsError(f"private build root already exists: {destination_root}")
299
+ destination_root.mkdir(parents=True, mode=0o700)
300
+ try:
301
+ for path, metadata in _tree_entries(source_root):
302
+ relative = path.relative_to(source_root)
303
+ target = destination_root / relative
304
+ if stat.S_ISDIR(metadata.st_mode):
305
+ target.mkdir(mode=stat.S_IMODE(metadata.st_mode) | 0o700)
306
+ else:
307
+ target.parent.mkdir(parents=True, exist_ok=True)
308
+ with (
309
+ path.open("rb") as source_handle,
310
+ target.open("xb") as target_handle,
311
+ ):
312
+ shutil.copyfileobj(source_handle, target_handle, length=1024 * 1024)
313
+ target_handle.flush()
314
+ os.fsync(target_handle.fileno())
315
+ target.chmod(stat.S_IMODE(metadata.st_mode))
316
+ validate_artifact_tree(destination_root)
317
+ except BaseException:
318
+ shutil.rmtree(destination_root, ignore_errors=True)
319
+ raise
320
+ return destination_root
321
+
322
+
323
+ def _compile_environment(
324
+ build_root: Path, data_root: Path, seed: int, timezone: str
325
+ ) -> dict[str, str]:
326
+ # This is an allowlist, not a copy of the verifier environment. In
327
+ # particular no provider, cloud, source, or hidden-fixture credential can
328
+ # reach compile.sh.
329
+ return {
330
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
331
+ "LANG": "C.UTF-8",
332
+ "LC_ALL": "C.UTF-8",
333
+ "HOST": "127.0.0.1",
334
+ "PORT": "3000",
335
+ "DATA_DIR": str(data_root),
336
+ "SEED": str(seed),
337
+ "TZ": timezone,
338
+ "HOME": str(data_root / "home"),
339
+ "TMPDIR": str(data_root / "tmp"),
340
+ "XDG_CACHE_HOME": str(data_root / "xdg-cache"),
341
+ "XDG_CONFIG_HOME": str(data_root / "xdg-config"),
342
+ "XDG_DATA_HOME": str(data_root / "xdg-data"),
343
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
344
+ "WEBSITEBENCH_BUILD_ROOT": str(build_root),
345
+ }
346
+
347
+
348
+ def _install_socket_deny_filter() -> None:
349
+ """Deny sockets and process-group escape while allowing compiler children."""
350
+
351
+ (
352
+ audit_arch,
353
+ socket_syscall,
354
+ _fcntl_syscall,
355
+ seccomp_syscall,
356
+ _denied,
357
+ ) = sandbox._architecture()
358
+ escape_syscalls = (109, 112) if audit_arch == 0xC000003E else (154, 157)
359
+ instructions = [
360
+ (sandbox.BPF_LD_W_ABS, 0, 0, 4),
361
+ (sandbox.BPF_JMP_JEQ_K, 1, 0, audit_arch),
362
+ (sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_KILL_PROCESS),
363
+ (sandbox.BPF_LD_W_ABS, 0, 0, 0),
364
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, socket_syscall),
365
+ (
366
+ sandbox.BPF_RET_K,
367
+ 0,
368
+ 0,
369
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
370
+ ),
371
+ ]
372
+ for syscall_number in escape_syscalls:
373
+ instructions.extend(
374
+ [
375
+ (sandbox.BPF_JMP_JEQ_K, 0, 1, syscall_number),
376
+ (
377
+ sandbox.BPF_RET_K,
378
+ 0,
379
+ 0,
380
+ sandbox.SECCOMP_RET_ERRNO | errno.EPERM,
381
+ ),
382
+ ]
383
+ )
384
+ instructions.append((sandbox.BPF_RET_K, 0, 0, sandbox.SECCOMP_RET_ALLOW))
385
+ filters = (sandbox._SockFilter * len(instructions))(
386
+ *(sandbox._SockFilter(*instruction) for instruction in instructions)
387
+ )
388
+ program = sandbox._SockFprog(len(instructions), filters)
389
+ libc = ctypes.CDLL(None, use_errno=True)
390
+ if libc.prctl(sandbox.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
391
+ raise OSError(ctypes.get_errno(), "cannot set compiler no_new_privs")
392
+ result = int(
393
+ libc.syscall(
394
+ seccomp_syscall,
395
+ sandbox.SECCOMP_SET_MODE_FILTER,
396
+ 0,
397
+ ctypes.byref(program),
398
+ )
399
+ )
400
+ if result != 0:
401
+ raise OSError(ctypes.get_errno(), "cannot install compiler network filter")
402
+
403
+
404
+ def _compiler_preexec(
405
+ build_root: Path, data_root: Path, memory_mb: int, cpu_seconds: int
406
+ ) -> None:
407
+ os.umask(0o077)
408
+ if resource is not None:
409
+ memory = memory_mb * 1024 * 1024
410
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
411
+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 5))
412
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
413
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
414
+ # Root and data are deliberately the same writable private tree for
415
+ # compilation. Landlock grants system toolchains read/execute access and
416
+ # grants no TCP bind/connect ports. It also withholds shared filesystem
417
+ # socket locations such as /run and /tmp.
418
+ sandbox._landlock(build_root, data_root, 1, set())
419
+ _install_socket_deny_filter()
420
+
421
+
422
+ def _process_group_alive(group: int) -> bool:
423
+ proc = Path("/proc")
424
+ if proc.is_dir():
425
+ for status_path in proc.glob("[0-9]*/stat"):
426
+ try:
427
+ raw = status_path.read_text(encoding="ascii")
428
+ fields = raw[raw.rfind(")") + 2 :].split()
429
+ if int(fields[2]) == group and fields[0] != "Z":
430
+ return True
431
+ except (OSError, UnicodeError, ValueError, IndexError):
432
+ continue
433
+ return False
434
+ try:
435
+ os.killpg(group, 0)
436
+ except (ProcessLookupError, PermissionError):
437
+ return False
438
+ return True
439
+
440
+
441
+ def _terminate_group(
442
+ process: subprocess.Popen[Any],
443
+ timeout: float = 10.0,
444
+ *,
445
+ accept_forced: bool = False,
446
+ ) -> bool:
447
+ group = process.pid
448
+ if process.poll() is None:
449
+ try:
450
+ os.killpg(group, signal.SIGTERM)
451
+ except ProcessLookupError:
452
+ pass
453
+ deadline = time.monotonic() + timeout
454
+ while _process_group_alive(group) and time.monotonic() < deadline:
455
+ time.sleep(0.02)
456
+ graceful = not _process_group_alive(group)
457
+ if not graceful:
458
+ try:
459
+ os.killpg(group, signal.SIGKILL)
460
+ except ProcessLookupError:
461
+ pass
462
+ try:
463
+ process.wait(timeout=5)
464
+ except subprocess.TimeoutExpired:
465
+ return False
466
+ terminated = not _process_group_alive(group)
467
+ return graceful or (accept_forced and terminated)
468
+
469
+
470
+ def _stop_controlled_group(
471
+ process: subprocess.Popen[Any],
472
+ control_fd: int,
473
+ timeout: float = 10.0,
474
+ *,
475
+ accept_forced: bool = False,
476
+ ) -> bool:
477
+ """Ask the trusted sandbox launcher to stop its tracee, then reap the group."""
478
+
479
+ if process.poll() is None:
480
+ try:
481
+ os.write(control_fd, b"T")
482
+ except OSError:
483
+ pass
484
+ deadline = time.monotonic() + timeout
485
+ while _process_group_alive(process.pid) and time.monotonic() < deadline:
486
+ time.sleep(0.02)
487
+ graceful = not _process_group_alive(process.pid)
488
+ if not graceful:
489
+ try:
490
+ os.write(control_fd, b"K")
491
+ except OSError:
492
+ pass
493
+ time.sleep(0.1)
494
+ if _process_group_alive(process.pid):
495
+ try:
496
+ os.killpg(process.pid, signal.SIGKILL)
497
+ except ProcessLookupError:
498
+ pass
499
+ try:
500
+ process.wait(timeout=5)
501
+ except subprocess.TimeoutExpired:
502
+ return False
503
+ terminated = not _process_group_alive(process.pid)
504
+ return graceful or (accept_forced and terminated)
505
+
506
+
507
+ def _processes_referencing(root: Path, *, exclude: Sequence[int] = ()) -> list[int]:
508
+ references: list[int] = []
509
+ root_text = str(root.resolve())
510
+ excluded = set(exclude)
511
+ for process in Path("/proc").glob("[0-9]*"):
512
+ try:
513
+ pid = int(process.name)
514
+ if pid in excluded:
515
+ continue
516
+ cwd = os.readlink(process / "cwd")
517
+ command = (
518
+ (process / "cmdline")
519
+ .read_bytes()
520
+ .replace(b"\x00", b" ")
521
+ .decode("utf-8", errors="replace")
522
+ )
523
+ except (OSError, ValueError):
524
+ continue
525
+ if (
526
+ cwd == root_text
527
+ or cwd.startswith(root_text + os.sep)
528
+ or root_text in command
529
+ ):
530
+ references.append(pid)
531
+ return sorted(references)
532
+
533
+
534
+ def tree_digest(root: Path | str) -> str:
535
+ resolved = Path(root).resolve(strict=True)
536
+ validate_artifact_tree(resolved)
537
+ digest = hashlib.sha256()
538
+ for path, metadata in _tree_entries(resolved):
539
+ relative = path.relative_to(resolved).as_posix().encode("utf-8")
540
+ kind = b"d" if stat.S_ISDIR(metadata.st_mode) else b"f"
541
+ digest.update(kind + b"\0" + relative + b"\0")
542
+ digest.update(f"{stat.S_IMODE(metadata.st_mode):04o}".encode("ascii") + b"\0")
543
+ if kind == b"f":
544
+ with path.open("rb") as handle:
545
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
546
+ digest.update(chunk)
547
+ digest.update(b"\0")
548
+ return digest.hexdigest()
549
+
550
+
551
+ def freeze_build_tree(root: Path | str) -> str:
552
+ resolved = Path(root).resolve(strict=True)
553
+ validate_artifact_tree(resolved)
554
+ entries = list(_tree_entries(resolved))
555
+ for path, metadata in entries:
556
+ if stat.S_ISREG(metadata.st_mode):
557
+ executable = bool(stat.S_IMODE(metadata.st_mode) & 0o111)
558
+ path.chmod(0o555 if executable else 0o444)
559
+ for path, metadata in reversed(entries):
560
+ if stat.S_ISDIR(metadata.st_mode):
561
+ path.chmod(0o555)
562
+ resolved.chmod(0o555)
563
+ return tree_digest(resolved)
564
+
565
+
566
+ def compile_candidate(
567
+ source_root: Path | str,
568
+ private_root: Path | str,
569
+ *,
570
+ timeout: float = DEFAULT_COMPILE_TIMEOUT,
571
+ seed: int = 0,
572
+ timezone: str = "UTC",
573
+ memory_mb: int = 8192,
574
+ ) -> CompiledArtifact:
575
+ """Quarantine, compile offline once, validate, freeze, and hash the build."""
576
+
577
+ source = Path(source_root).resolve(strict=True)
578
+ private = Path(private_root).resolve()
579
+ if private.exists():
580
+ raise FileExistsError(f"private compiler root already exists: {private}")
581
+ private.mkdir(parents=True, mode=0o700)
582
+ build = private / "build"
583
+ log = private / "build.log"
584
+ quarantine_artifact(source, build)
585
+ data = build / ".websitebench-compile-data"
586
+ if data.exists():
587
+ if data.is_dir() and not data.is_symlink():
588
+ shutil.rmtree(data)
589
+ else:
590
+ data.unlink()
591
+ data.mkdir(mode=0o700)
592
+ for name in ("home", "tmp", "xdg-cache", "xdg-config", "xdg-data"):
593
+ (data / name).mkdir(mode=0o700)
594
+ compile_script = build / COMPILE_ENTRYPOINT
595
+ if not compile_script.is_file() or compile_script.is_symlink():
596
+ raise CompilerSandboxError("candidate root must contain regular compile.sh")
597
+ if compile_script.stat().st_nlink != 1 or not os.access(compile_script, os.X_OK):
598
+ raise CompilerSandboxError("compile.sh must be an independent executable file")
599
+
600
+ # A submitted executable is never trusted as compiler output.
601
+ preexisting = build / EXECUTABLE_ENTRYPOINT
602
+ if preexisting.exists():
603
+ if preexisting.is_dir():
604
+ shutil.rmtree(preexisting)
605
+ else:
606
+ preexisting.unlink()
607
+
608
+ environment = _compile_environment(build, data, seed, timezone)
609
+ with log.open("wb") as log_handle:
610
+ try:
611
+ process = subprocess.Popen(
612
+ [str(compile_script)],
613
+ cwd=build,
614
+ env=environment,
615
+ stdin=subprocess.DEVNULL,
616
+ stdout=log_handle,
617
+ stderr=subprocess.STDOUT,
618
+ start_new_session=True,
619
+ preexec_fn=lambda: _compiler_preexec(
620
+ build, build, memory_mb, max(1, int(timeout))
621
+ ),
622
+ )
623
+ try:
624
+ return_code = process.wait(timeout=timeout)
625
+ except subprocess.TimeoutExpired as exc:
626
+ _terminate_group(process)
627
+ raise CompilerSandboxError(
628
+ f"compile.sh exceeded {timeout:g} seconds"
629
+ ) from exc
630
+ if _process_group_alive(process.pid):
631
+ _terminate_group(process)
632
+ raise CompilerSandboxError(
633
+ "compile.sh left a child process or listener alive"
634
+ )
635
+ if return_code != 0:
636
+ raise CompilerSandboxError(f"compile.sh exited {return_code}")
637
+ finally:
638
+ log_handle.flush()
639
+ os.fsync(log_handle.fileno())
640
+
641
+ leaked = _processes_referencing(build, exclude=(os.getpid(),))
642
+ if leaked:
643
+ for pid in leaked:
644
+ try:
645
+ os.kill(pid, signal.SIGKILL)
646
+ except ProcessLookupError:
647
+ pass
648
+ raise CompilerSandboxError(f"compiler left detached processes: {leaked}")
649
+ if log.stat().st_size > MAX_LOG_BYTES:
650
+ raise CompilerSandboxError("compiler log exceeded 256 MiB")
651
+
652
+ shutil.rmtree(data)
653
+ validate_artifact_tree(build)
654
+ executable = build / EXECUTABLE_ENTRYPOINT
655
+ try:
656
+ metadata = executable.lstat()
657
+ except OSError as exc:
658
+ raise CompilerSandboxError(
659
+ "compile.sh did not produce root executable"
660
+ ) from exc
661
+ if (
662
+ not stat.S_ISREG(metadata.st_mode)
663
+ or metadata.st_nlink != 1
664
+ or not stat.S_IMODE(metadata.st_mode) & 0o111
665
+ or executable.resolve() != executable
666
+ ):
667
+ raise CompilerSandboxError(
668
+ "executable must be an independent regular executable at the build root"
669
+ )
670
+ digest = freeze_build_tree(build)
671
+ return CompiledArtifact(
672
+ source_root=source,
673
+ build_root=build,
674
+ executable=executable,
675
+ tree_sha256=digest,
676
+ build_log=log,
677
+ )
678
+
679
+
680
+ @dataclass
681
+ class ExecutableRuntime:
682
+ """One foreground compiled candidate bound to one isolated DATA_DIR."""
683
+
684
+ build_root: Path
685
+ data_dir: Path
686
+ port: int
687
+ seed: int
688
+ timezone: str = "UTC"
689
+ log_path: Path | None = None
690
+ # RLIMIT_AS covers reserved virtual address space, not resident memory.
691
+ # Current Node/V8 runtimes reserve more than the 8192 MiB Harbor RSS
692
+ # budget before serving any request; keep the evaluator's cgroup budget
693
+ # authoritative while leaving enough address space for that reservation.
694
+ memory_mb: int = 16384
695
+ expected_tree_sha256: str | None = None
696
+ mailbox_environment: Mapping[str, str] | None = None
697
+ mailbox_connect_ports: frozenset[int] = frozenset()
698
+ evaluator_environment: Mapping[str, str] | None = None
699
+ worker_access_roots: tuple[Path, ...] = ()
700
+ process: subprocess.Popen[bytes] | None = None
701
+ _log_handle: Any | None = None
702
+ _cleanup_complete: bool = True
703
+ _control_write_fd: int | None = None
704
+ _broker_tid: int | None = None
705
+ _candidate_pid: int | None = None
706
+
707
+ def _environment(self) -> dict[str, str]:
708
+ data = self.data_dir.resolve()
709
+ environment = {
710
+ "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
711
+ "LANG": "C.UTF-8",
712
+ "LC_ALL": "C.UTF-8",
713
+ "HOST": "127.0.0.1",
714
+ "PORT": str(self.port),
715
+ "DATA_DIR": str(data),
716
+ "SEED": str(self.seed),
717
+ "TZ": self.timezone,
718
+ "HOME": str(data / "home"),
719
+ "TMPDIR": str(data / "tmp"),
720
+ "XDG_CACHE_HOME": str(data / "xdg-cache"),
721
+ "XDG_CONFIG_HOME": str(data / "xdg-config"),
722
+ "XDG_DATA_HOME": str(data / "xdg-data"),
723
+ "WEBSITEBENCH_DEPLOYMENT_ABI": DEPLOYMENT_ABI,
724
+ }
725
+ if self.mailbox_environment is not None:
726
+ unknown = set(self.mailbox_environment) - CANDIDATE_MAIL_ENVIRONMENT
727
+ if unknown:
728
+ raise CompilerSandboxError(
729
+ f"candidate mailbox environment has unknown names: {sorted(unknown)}"
730
+ )
731
+ environment.update(
732
+ {name: str(value) for name, value in self.mailbox_environment.items()}
733
+ )
734
+ if self.evaluator_environment is not None:
735
+ unknown = set(self.evaluator_environment) - CANDIDATE_EVALUATOR_ENVIRONMENT
736
+ if unknown:
737
+ raise CompilerSandboxError(
738
+ "candidate evaluator environment has unknown names: "
739
+ f"{sorted(unknown)}"
740
+ )
741
+ if any(not str(value) for value in self.evaluator_environment.values()):
742
+ raise CompilerSandboxError(
743
+ "candidate evaluator environment values must be non-empty"
744
+ )
745
+ environment.update(
746
+ {name: str(value) for name, value in self.evaluator_environment.items()}
747
+ )
748
+ return environment
749
+
750
+ def _sandbox_command(
751
+ self,
752
+ *,
753
+ build: Path,
754
+ executable: Path,
755
+ control_read_fd: int,
756
+ broker_write_fd: int,
757
+ credentials: tuple[int, int] | None,
758
+ ) -> list[str]:
759
+ sandbox_path = Path(sandbox.__file__).resolve(strict=True)
760
+ command = [
761
+ os.sys.executable,
762
+ str(sandbox_path),
763
+ "--root",
764
+ str(build),
765
+ "--data",
766
+ str(self.data_dir.resolve()),
767
+ "--bind-port",
768
+ str(self.port),
769
+ "--connect-port",
770
+ str(self.port),
771
+ ]
772
+ for connect_port in sorted(self.mailbox_connect_ports):
773
+ command.extend(("--connect-port", str(connect_port)))
774
+ if credentials is not None:
775
+ uid, gid = credentials
776
+ command.extend(("--uid", str(uid), "--gid", str(gid)))
777
+ command.extend(
778
+ (
779
+ "--file-size-limit-bytes",
780
+ str(MAX_LOG_BYTES),
781
+ "--broker-tid-fd",
782
+ str(broker_write_fd),
783
+ "--control-fd",
784
+ str(control_read_fd),
785
+ "--",
786
+ str(executable),
787
+ )
788
+ )
789
+ return command
790
+
791
+ def _attest_worker_identity(
792
+ self,
793
+ *,
794
+ expected_uid: int,
795
+ expected_gid: int,
796
+ ) -> None:
797
+ if self.process is None or self._broker_tid is None or self._candidate_pid is None:
798
+ raise OSError(errno.EIO, "sandbox identity proof is incomplete")
799
+ launcher_pid = self.process.pid
800
+ broker_status = Path(
801
+ f"/proc/{launcher_pid}/task/{self._broker_tid}/status"
802
+ )
803
+ candidate_status = Path(f"/proc/{self._candidate_pid}/status")
804
+ broker_uid, broker_gid, _broker_parent = _proc_status_identity(broker_status)
805
+ candidate_uid, candidate_gid, candidate_parent = _proc_status_identity(
806
+ candidate_status
807
+ )
808
+ expected_uids = (expected_uid,) * 4
809
+ expected_gids = (expected_gid,) * 4
810
+ if (
811
+ broker_uid != expected_uids
812
+ or broker_gid != expected_gids
813
+ or candidate_uid != expected_uids
814
+ or candidate_gid != expected_gids
815
+ or candidate_parent != launcher_pid
816
+ ):
817
+ raise OSError(
818
+ errno.EPERM,
819
+ "sandbox broker or candidate retained an unexpected OS identity",
820
+ )
821
+
822
+ def _preexec(self) -> None:
823
+ os.umask(0o077)
824
+ if resource is not None:
825
+ memory = self.memory_mb * 1024 * 1024
826
+ resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
827
+ resource.setrlimit(resource.RLIMIT_NOFILE, (1024, 1024))
828
+ resource.setrlimit(resource.RLIMIT_FSIZE, (MAX_LOG_BYTES, MAX_LOG_BYTES))
829
+
830
+ def start(self) -> None:
831
+ if not self._cleanup_complete:
832
+ raise CompilerSandboxError(
833
+ "runtime cleanup is incomplete; restart forbidden"
834
+ )
835
+ if self.process is not None and self.process.poll() is None:
836
+ raise CompilerSandboxError("compiled runtime is already running")
837
+ for connect_port in self.mailbox_connect_ports:
838
+ if not 1 <= connect_port <= 65535 or connect_port == self.port:
839
+ raise CompilerSandboxError("candidate mailbox connect port is invalid")
840
+ build = self.build_root.resolve(strict=True)
841
+ current_digest = tree_digest(build)
842
+ if current_digest == "": # pragma: no cover - digest is never empty
843
+ raise CompilerSandboxError("compiled build hash is unavailable")
844
+ if (
845
+ self.expected_tree_sha256 is not None
846
+ and current_digest != self.expected_tree_sha256
847
+ ):
848
+ raise CompilerSandboxError("compiled build tree changed after freezing")
849
+ executable = build / EXECUTABLE_ENTRYPOINT
850
+ metadata = executable.lstat()
851
+ if not stat.S_ISREG(metadata.st_mode) or not metadata.st_mode & 0o111:
852
+ raise CompilerSandboxError("compiled executable contract changed")
853
+ credentials = _runtime_worker_credentials()
854
+ try:
855
+ _prepare_runtime_directories(
856
+ build,
857
+ self.data_dir.resolve(),
858
+ credentials,
859
+ worker_access_roots=self.worker_access_roots,
860
+ )
861
+ except OSError as exc:
862
+ raise RuntimeInfrastructureError(
863
+ "compiled runtime worker directories could not be prepared"
864
+ ) from exc
865
+ if self.log_path is not None:
866
+ log = self.log_path.resolve()
867
+ data = self.data_dir.resolve()
868
+ if data not in log.parents:
869
+ raise CompilerSandboxError("runtime log must be inside DATA_DIR")
870
+ log.parent.mkdir(parents=True, exist_ok=True)
871
+ self._log_handle = log.open("ab")
872
+ control_read_fd, control_write_fd = os.pipe()
873
+ broker_read_fd, broker_write_fd = os.pipe()
874
+ os.set_blocking(broker_read_fd, False)
875
+ command = self._sandbox_command(
876
+ build=build,
877
+ executable=executable,
878
+ control_read_fd=control_read_fd,
879
+ broker_write_fd=broker_write_fd,
880
+ credentials=credentials,
881
+ )
882
+ try:
883
+ self.process = subprocess.Popen(
884
+ command,
885
+ cwd=build,
886
+ env=self._environment(),
887
+ stdin=subprocess.DEVNULL,
888
+ stdout=self._log_handle or subprocess.DEVNULL,
889
+ stderr=self._log_handle or subprocess.DEVNULL,
890
+ start_new_session=True,
891
+ preexec_fn=self._preexec,
892
+ pass_fds=(control_read_fd, broker_write_fd),
893
+ )
894
+ except BaseException:
895
+ os.close(control_read_fd)
896
+ os.close(control_write_fd)
897
+ os.close(broker_read_fd)
898
+ os.close(broker_write_fd)
899
+ self._close_log()
900
+ raise
901
+ os.close(control_read_fd)
902
+ os.close(broker_write_fd)
903
+ self._control_write_fd = control_write_fd
904
+ self._cleanup_complete = False
905
+ proof = b""
906
+ # Process creation can be delayed materially when several Harbor
907
+ # verifier shards contend for I/O. Identity proof is an
908
+ # infrastructure handshake, not candidate readiness, so give the
909
+ # trusted launcher enough time to report its already-created workers.
910
+ deadline = time.monotonic() + 15.0
911
+ try:
912
+ while b"\n" not in proof and time.monotonic() < deadline:
913
+ try:
914
+ proof += os.read(broker_read_fd, 128)
915
+ except BlockingIOError:
916
+ pass
917
+ if self.process.poll() is not None:
918
+ break
919
+ time.sleep(0.01)
920
+ except OSError as exc:
921
+ self.stop(timeout=1.0)
922
+ raise RuntimeInfrastructureError(
923
+ "compiled runtime sandbox identity proof could not be read"
924
+ ) from exc
925
+ finally:
926
+ os.close(broker_read_fd)
927
+ try:
928
+ proof_fields = proof.splitlines()[0].split()
929
+ if len(proof_fields) != 2:
930
+ raise ValueError("sandbox proof must contain two process IDs")
931
+ self._broker_tid, self._candidate_pid = map(int, proof_fields)
932
+ except (ValueError, IndexError):
933
+ self._broker_tid = None
934
+ self._candidate_pid = None
935
+ if (
936
+ self._broker_tid is not None
937
+ and not Path(f"/proc/{self.process.pid}/task/{self._broker_tid}").is_dir()
938
+ ):
939
+ self._broker_tid = None
940
+ if self._broker_tid is None or self._candidate_pid is None:
941
+ self.stop(timeout=1.0)
942
+ raise RuntimeInfrastructureError(
943
+ "compiled runtime sandbox did not attest its broker and candidate IDs"
944
+ )
945
+ expected_uid, expected_gid = credentials or (os.geteuid(), os.getegid())
946
+ try:
947
+ self._attest_worker_identity(
948
+ expected_uid=expected_uid,
949
+ expected_gid=expected_gid,
950
+ )
951
+ except OSError as exc:
952
+ self.stop(timeout=1.0)
953
+ raise RuntimeInfrastructureError(
954
+ "compiled runtime sandbox worker identity could not be verified"
955
+ ) from exc
956
+
957
+ def ready(self, *, timeout: float = 30.0) -> bool:
958
+ deadline = time.monotonic() + timeout
959
+ urls = [f"http://127.0.0.1:{self.port}{path}" for path in HEALTH_PATHS]
960
+ while time.monotonic() < deadline:
961
+ if self.process is None or self.process.poll() is not None:
962
+ return False
963
+ for url in urls:
964
+ try:
965
+ request = urllib.request.Request(url, method="GET")
966
+ with urllib.request.urlopen(request, timeout=0.5) as response:
967
+ payload = response.read(4096)
968
+ if (
969
+ response.status == 200
970
+ and json.loads(payload) == HEALTH_BODY
971
+ ):
972
+ return self.process.poll() is None
973
+ except (
974
+ OSError,
975
+ ValueError,
976
+ urllib.error.URLError,
977
+ json.JSONDecodeError,
978
+ ):
979
+ pass
980
+ time.sleep(0.05)
981
+ return False
982
+
983
+ def stop(
984
+ self, *, timeout: float = 10.0, accept_forced: bool = False
985
+ ) -> bool:
986
+ if self.process is None:
987
+ self._close_control()
988
+ self._close_log()
989
+ self._cleanup_complete = True
990
+ return True
991
+ if self._control_write_fd is None:
992
+ graceful = _terminate_group(
993
+ self.process, timeout, accept_forced=accept_forced
994
+ )
995
+ else:
996
+ graceful = _stop_controlled_group(
997
+ self.process,
998
+ self._control_write_fd,
999
+ timeout,
1000
+ accept_forced=accept_forced,
1001
+ )
1002
+ self._close_control()
1003
+ self._close_log()
1004
+ self._cleanup_complete = graceful
1005
+ self._broker_tid = None
1006
+ self._candidate_pid = None
1007
+ return graceful
1008
+
1009
+ def _close_control(self) -> None:
1010
+ if self._control_write_fd is not None:
1011
+ try:
1012
+ os.close(self._control_write_fd)
1013
+ except OSError:
1014
+ pass
1015
+ self._control_write_fd = None
1016
+
1017
+ def _close_log(self) -> None:
1018
+ if self._log_handle is not None:
1019
+ self._log_handle.flush()
1020
+ os.fsync(self._log_handle.fileno())
1021
+ self._log_handle.close()
1022
+ self._log_handle = None
1023
+
1024
+
1025
+ def validate_runtime_lifecycle(
1026
+ artifact: CompiledArtifact,
1027
+ *,
1028
+ port: int,
1029
+ seed: int,
1030
+ working_root: Path | str,
1031
+ worker_access_roots: Sequence[Path | str],
1032
+ timezone: str = "UTC",
1033
+ ) -> dict[str, Any]:
1034
+ """Probe health, foreground/SIGTERM, restart persistence and new-dir isolation."""
1035
+
1036
+ root = Path(working_root).resolve()
1037
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
1038
+ first_data = root / "data-first"
1039
+ second_data = root / "data-second"
1040
+ first_data.mkdir(mode=0o700)
1041
+ second_data.mkdir(mode=0o700)
1042
+ sentinel = first_data / ".websitebench-persistence"
1043
+ sentinel.write_text(f"{seed}\n", encoding="ascii")
1044
+ first = ExecutableRuntime(
1045
+ artifact.build_root,
1046
+ first_data,
1047
+ port,
1048
+ seed,
1049
+ timezone,
1050
+ first_data / "runtime.log",
1051
+ expected_tree_sha256=artifact.tree_sha256,
1052
+ worker_access_roots=tuple(Path(value) for value in worker_access_roots),
1053
+ )
1054
+ first.start()
1055
+ healthy = first.ready()
1056
+ graceful = first.stop(timeout=10.0)
1057
+ sentinel_persisted = sentinel.read_text(encoding="ascii") == f"{seed}\n"
1058
+ restarted = False
1059
+ if graceful:
1060
+ first.start()
1061
+ restarted = first.ready()
1062
+ graceful = first.stop(timeout=10.0) and graceful
1063
+ second = ExecutableRuntime(
1064
+ artifact.build_root,
1065
+ second_data,
1066
+ port,
1067
+ seed,
1068
+ timezone,
1069
+ second_data / "runtime.log",
1070
+ expected_tree_sha256=artifact.tree_sha256,
1071
+ worker_access_roots=tuple(Path(value) for value in worker_access_roots),
1072
+ )
1073
+ second.start()
1074
+ second_healthy = second.ready()
1075
+ second_graceful = second.stop(timeout=10.0)
1076
+ isolated = (
1077
+ second_healthy
1078
+ and second_graceful
1079
+ and not (second_data / sentinel.name).exists()
1080
+ )
1081
+ return {
1082
+ "deployment_abi": DEPLOYMENT_ABI,
1083
+ "health": healthy,
1084
+ "foreground": healthy,
1085
+ "sigterm": graceful,
1086
+ "restart": restarted,
1087
+ "persistence": sentinel_persisted,
1088
+ "new_data_dir_health": second_healthy,
1089
+ "new_data_dir_isolation": isolated,
1090
+ "tree_sha256": artifact.tree_sha256,
1091
+ "valid": all(
1092
+ (
1093
+ healthy,
1094
+ graceful,
1095
+ restarted,
1096
+ sentinel_persisted,
1097
+ second_healthy,
1098
+ second_graceful,
1099
+ isolated,
1100
+ )
1101
+ ),
1102
+ }
1103
+
1104
+
1105
+ __all__ = [
1106
+ "COMPILE_ENTRYPOINT",
1107
+ "DEFAULT_COMPILE_TIMEOUT",
1108
+ "DEPLOYMENT_ABI",
1109
+ "EXECUTABLE_ENTRYPOINT",
1110
+ "HEALTH_BODY",
1111
+ "HEALTH_PATH",
1112
+ "HEALTH_PATHS",
1113
+ "LEGACY_HEALTH_PATHS",
1114
+ "MAX_LOG_BYTES",
1115
+ "RUNTIME_PROCESS_MODEL",
1116
+ "RuntimeInfrastructureError",
1117
+ "WORKER_OS_GID",
1118
+ "WORKER_OS_UID",
1119
+ "CompiledArtifact",
1120
+ "CompilerSandboxError",
1121
+ "ExecutableRuntime",
1122
+ "compile_candidate",
1123
+ "freeze_build_tree",
1124
+ "quarantine_artifact",
1125
+ "tree_digest",
1126
+ "validate_artifact_tree",
1127
+ "validate_runtime_lifecycle",
1128
+ ]
tasks/brooklinen/environment/candidate-abi/websitebench/harbor/sandbox.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux kernel sandbox launcher for untrusted Harbor candidates.
2
+
3
+ The launcher is executed by the privileged verifier, installs an irreversible
4
+ Landlock/seccomp policy, drops to the opaque worker UID, and only then execs the
5
+ candidate entrypoint. It deliberately has no dependency outside the standard
6
+ library so the formal verifier image has a small, inspectable trusted surface.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import array
13
+ import ctypes
14
+ import errno
15
+ import fcntl
16
+ import os
17
+ import platform
18
+ import resource
19
+ import signal
20
+ import socket
21
+ import stat
22
+ import struct
23
+ import threading
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Sequence
27
+
28
+
29
+ PR_SET_NO_NEW_PRIVS = 38
30
+ PR_SET_DUMPABLE = 4
31
+ PR_SET_SECCOMP = 22
32
+ SECCOMP_MODE_FILTER = 2
33
+ SECCOMP_RET_KILL_PROCESS = 0x80000000
34
+ SECCOMP_RET_ERRNO = 0x00050000
35
+ SECCOMP_RET_USER_NOTIF = 0x7FC00000
36
+ SECCOMP_RET_ALLOW = 0x7FFF0000
37
+ SECCOMP_FILTER_FLAG_NEW_LISTENER = 1 << 3
38
+ SECCOMP_SET_MODE_FILTER = 1
39
+ SECCOMP_GET_ACTION_AVAIL = 2
40
+
41
+ BPF_LD_W_ABS = 0x20
42
+ BPF_JMP_JEQ_K = 0x15
43
+ BPF_JMP_JSET_K = 0x45
44
+ BPF_ALU_AND_K = 0x54
45
+ BPF_RET_K = 0x06
46
+
47
+ LANDLOCK_CREATE_RULESET_VERSION = 1
48
+ LANDLOCK_RULE_PATH_BENEATH = 1
49
+ LANDLOCK_RULE_NET_PORT = 2
50
+ LANDLOCK_ACCESS_FS_EXECUTE = 1 << 0
51
+ LANDLOCK_ACCESS_FS_WRITE_FILE = 1 << 1
52
+ LANDLOCK_ACCESS_FS_READ_FILE = 1 << 2
53
+ LANDLOCK_ACCESS_FS_READ_DIR = 1 << 3
54
+ LANDLOCK_ACCESS_FS_REMOVE_DIR = 1 << 4
55
+ LANDLOCK_ACCESS_FS_REMOVE_FILE = 1 << 5
56
+ LANDLOCK_ACCESS_FS_MAKE_CHAR = 1 << 6
57
+ LANDLOCK_ACCESS_FS_MAKE_DIR = 1 << 7
58
+ LANDLOCK_ACCESS_FS_MAKE_REG = 1 << 8
59
+ LANDLOCK_ACCESS_FS_MAKE_SOCK = 1 << 9
60
+ LANDLOCK_ACCESS_FS_MAKE_FIFO = 1 << 10
61
+ LANDLOCK_ACCESS_FS_MAKE_BLOCK = 1 << 11
62
+ LANDLOCK_ACCESS_FS_MAKE_SYM = 1 << 12
63
+ LANDLOCK_ACCESS_FS_REFER = 1 << 13
64
+ LANDLOCK_ACCESS_FS_TRUNCATE = 1 << 14
65
+ LANDLOCK_ACCESS_FS_IOCTL_DEV = 1 << 15
66
+ LANDLOCK_ACCESS_NET_BIND_TCP = 1 << 0
67
+ LANDLOCK_ACCESS_NET_CONNECT_TCP = 1 << 1
68
+
69
+ _FS_ABI_1 = (1 << 13) - 1
70
+ _FS_ABI_2 = _FS_ABI_1 | LANDLOCK_ACCESS_FS_REFER
71
+ _FS_ABI_3 = _FS_ABI_2 | LANDLOCK_ACCESS_FS_TRUNCATE
72
+ _FS_ABI_5 = _FS_ABI_3 | LANDLOCK_ACCESS_FS_IOCTL_DEV
73
+ _FS_READ_EXECUTE = (
74
+ LANDLOCK_ACCESS_FS_EXECUTE
75
+ | LANDLOCK_ACCESS_FS_READ_FILE
76
+ | LANDLOCK_ACCESS_FS_READ_DIR
77
+ )
78
+
79
+
80
+ class _RulesetAttr(ctypes.Structure):
81
+ _fields_ = [
82
+ ("handled_access_fs", ctypes.c_uint64),
83
+ ("handled_access_net", ctypes.c_uint64),
84
+ ]
85
+
86
+
87
+ class _PathBeneathAttr(ctypes.Structure):
88
+ _fields_ = [
89
+ ("allowed_access", ctypes.c_uint64),
90
+ ("parent_fd", ctypes.c_int32),
91
+ ("reserved", ctypes.c_uint32),
92
+ ]
93
+
94
+
95
+ class _NetPortAttr(ctypes.Structure):
96
+ _fields_ = [("allowed_access", ctypes.c_uint64), ("port", ctypes.c_uint64)]
97
+
98
+
99
+ class _SockFilter(ctypes.Structure):
100
+ _fields_ = [
101
+ ("code", ctypes.c_ushort),
102
+ ("jt", ctypes.c_ubyte),
103
+ ("jf", ctypes.c_ubyte),
104
+ ("k", ctypes.c_uint32),
105
+ ]
106
+
107
+
108
+ class _SockFprog(ctypes.Structure):
109
+ _fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.POINTER(_SockFilter))]
110
+
111
+
112
+ _SECCOMP_NOTIF_FORMAT = "=QIIiIQQQQQQQ"
113
+ _SECCOMP_RESP_FORMAT = "=QqiI"
114
+ _SECCOMP_NOTIF_SIZE = struct.calcsize(_SECCOMP_NOTIF_FORMAT)
115
+ _SECCOMP_RESP_SIZE = struct.calcsize(_SECCOMP_RESP_FORMAT)
116
+
117
+
118
+ def _iowr(kind: int, number: int, size: int) -> int:
119
+ return (3 << 30) | (size << 16) | (kind << 8) | number
120
+
121
+
122
+ _SECCOMP_IOCTL_NOTIF_RECV = _iowr(ord("!"), 0, _SECCOMP_NOTIF_SIZE)
123
+ _SECCOMP_IOCTL_NOTIF_SEND = _iowr(ord("!"), 1, _SECCOMP_RESP_SIZE)
124
+
125
+
126
+ def _architecture() -> tuple[int, int, int, int, tuple[int, ...]]:
127
+ machine = platform.machine().lower()
128
+ if machine in {"x86_64", "amd64"}:
129
+ # AUDIT_ARCH_X86_64, socket(2), and shared cross-process facilities.
130
+ return (
131
+ 0xC000003E,
132
+ 41,
133
+ 72,
134
+ 317,
135
+ (
136
+ 29,
137
+ 30,
138
+ 31,
139
+ 57,
140
+ 58,
141
+ 64,
142
+ 65,
143
+ 66,
144
+ 67,
145
+ 68,
146
+ 69,
147
+ 70,
148
+ 71,
149
+ 109,
150
+ 112,
151
+ 240,
152
+ 241,
153
+ 242,
154
+ 243,
155
+ 244,
156
+ 245,
157
+ 248,
158
+ 249,
159
+ 250,
160
+ 253,
161
+ 254,
162
+ 255,
163
+ 294,
164
+ 298,
165
+ 300,
166
+ 301,
167
+ 425,
168
+ 73,
169
+ ),
170
+ )
171
+ if machine in {"aarch64", "arm64"}:
172
+ return (
173
+ 0xC00000B7,
174
+ 198,
175
+ 25,
176
+ 277,
177
+ tuple(range(180, 198))
178
+ + (26, 27, 28, 32, 154, 157, 217, 218, 219, 241, 262, 263, 425),
179
+ )
180
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
181
+
182
+
183
+ def _syscalls() -> tuple[int, int, int]:
184
+ machine = platform.machine().lower()
185
+ if machine in {"x86_64", "amd64", "aarch64", "arm64"}:
186
+ return 444, 445, 446
187
+ raise OSError(errno.ENOTSUP, f"unsupported verifier architecture: {machine}")
188
+
189
+
190
+ def sandbox_runtime_fingerprint() -> dict[str, object]:
191
+ """Return trusted kernel capabilities required by the candidate sandbox."""
192
+
193
+ audit_arch, socket_syscall, _fcntl_syscall, seccomp_syscall, _denied = (
194
+ _architecture()
195
+ )
196
+ create_ruleset, _add_rule, _restrict_self = _syscalls()
197
+ libc = ctypes.CDLL(None, use_errno=True)
198
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
199
+ action = ctypes.c_uint32(SECCOMP_RET_USER_NOTIF)
200
+ user_notification = (
201
+ libc.syscall(
202
+ seccomp_syscall,
203
+ SECCOMP_GET_ACTION_AVAIL,
204
+ 0,
205
+ ctypes.byref(action),
206
+ )
207
+ == 0
208
+ )
209
+ x32_unavailable = True
210
+ if audit_arch == 0xC000003E:
211
+ ctypes.set_errno(0)
212
+ result = libc.syscall(0x40000000 | socket_syscall, -1, -1, -1)
213
+ x32_unavailable = result == -1 and ctypes.get_errno() == errno.ENOSYS
214
+ return {
215
+ "schema": "websitebench.harbor.sandbox-runtime",
216
+ "architecture": platform.machine().lower(),
217
+ "landlock_abi": abi,
218
+ "seccomp_user_notification": user_notification,
219
+ "x32_unavailable": x32_unavailable,
220
+ }
221
+
222
+
223
+ def sandbox_preflight() -> dict[str, object]:
224
+ """Fail closed before scoring when the verifier kernel cannot sandbox."""
225
+
226
+ fingerprint = sandbox_runtime_fingerprint()
227
+ if (
228
+ int(fingerprint["landlock_abi"]) < 4
229
+ or fingerprint["seccomp_user_notification"] is not True
230
+ or fingerprint["x32_unavailable"] is not True
231
+ ):
232
+ raise OSError(errno.ENOTSUP, f"candidate sandbox unavailable: {fingerprint}")
233
+ child = os.fork()
234
+ if child == 0:
235
+ try:
236
+ _landlock(Path("/"), Path("/tmp"), 65534, {65534})
237
+ listener = _seccomp()
238
+ os.close(listener)
239
+ os._exit(0)
240
+ except BaseException:
241
+ os._exit(1)
242
+ _waited, status = os.waitpid(child, 0)
243
+ if not os.WIFEXITED(status) or os.WEXITSTATUS(status) != 0:
244
+ raise OSError(errno.ENOTSUP, "candidate sandbox enforcement probe failed")
245
+ fingerprint["enforcement_probe_passed"] = True
246
+ return fingerprint
247
+
248
+
249
+ def _landlock(
250
+ root: Path,
251
+ data: Path,
252
+ bind_port: int,
253
+ connect_ports: set[int],
254
+ read_paths: Sequence[Path] = (),
255
+ ) -> None:
256
+ libc = ctypes.CDLL(None, use_errno=True)
257
+ create_ruleset, add_rule, restrict_self = _syscalls()
258
+ abi = int(libc.syscall(create_ruleset, 0, 0, LANDLOCK_CREATE_RULESET_VERSION))
259
+ if abi < 4:
260
+ code = ctypes.get_errno() if abi < 0 else errno.ENOTSUP
261
+ raise OSError(code, "Landlock ABI 4 or newer is required")
262
+
263
+ handled_fs = _FS_ABI_1
264
+ if abi >= 2:
265
+ handled_fs = _FS_ABI_2
266
+ if abi >= 3:
267
+ handled_fs = _FS_ABI_3
268
+ if abi >= 5:
269
+ handled_fs = _FS_ABI_5
270
+ handled_net = LANDLOCK_ACCESS_NET_BIND_TCP | LANDLOCK_ACCESS_NET_CONNECT_TCP
271
+ attributes = _RulesetAttr(handled_fs, handled_net)
272
+ ruleset_fd = int(
273
+ libc.syscall(
274
+ create_ruleset,
275
+ ctypes.byref(attributes),
276
+ ctypes.sizeof(attributes),
277
+ 0,
278
+ )
279
+ )
280
+ if ruleset_fd < 0:
281
+ raise OSError(ctypes.get_errno(), "cannot create Landlock ruleset")
282
+
283
+ def add_path(path: Path, access: int) -> None:
284
+ if not path.exists():
285
+ return
286
+ descriptor = os.open(path, os.O_PATH | os.O_CLOEXEC)
287
+ try:
288
+ rule = _PathBeneathAttr(access & handled_fs, descriptor, 0)
289
+ if (
290
+ libc.syscall(
291
+ add_rule,
292
+ ruleset_fd,
293
+ LANDLOCK_RULE_PATH_BENEATH,
294
+ ctypes.byref(rule),
295
+ 0,
296
+ )
297
+ != 0
298
+ ):
299
+ raise OSError(ctypes.get_errno(), f"cannot allow sandbox path: {path}")
300
+ finally:
301
+ os.close(descriptor)
302
+
303
+ try:
304
+ for path in (
305
+ root,
306
+ Path("/usr"),
307
+ Path("/bin"),
308
+ Path("/lib"),
309
+ Path("/lib64"),
310
+ Path("/etc"),
311
+ *read_paths,
312
+ ):
313
+ add_path(path, _FS_READ_EXECUTE)
314
+ for path in (
315
+ Path("/dev/null"),
316
+ Path("/dev/zero"),
317
+ Path("/dev/random"),
318
+ Path("/dev/urandom"),
319
+ Path("/dev/full"),
320
+ Path("/dev/tty"),
321
+ ):
322
+ add_path(path, LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE)
323
+ add_path(data, handled_fs)
324
+
325
+ for access, port in (
326
+ (LANDLOCK_ACCESS_NET_BIND_TCP, bind_port),
327
+ *(
328
+ (LANDLOCK_ACCESS_NET_CONNECT_TCP, port)
329
+ for port in sorted(connect_ports)
330
+ ),
331
+ ):
332
+ rule = _NetPortAttr(access, port)
333
+ if (
334
+ libc.syscall(
335
+ add_rule,
336
+ ruleset_fd,
337
+ LANDLOCK_RULE_NET_PORT,
338
+ ctypes.byref(rule),
339
+ 0,
340
+ )
341
+ != 0
342
+ ):
343
+ raise OSError(ctypes.get_errno(), "cannot add Landlock TCP rule")
344
+
345
+ if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
346
+ raise OSError(ctypes.get_errno(), "cannot set no_new_privs")
347
+ if libc.syscall(restrict_self, ruleset_fd, 0) != 0:
348
+ raise OSError(ctypes.get_errno(), "cannot enforce Landlock ruleset")
349
+ finally:
350
+ os.close(ruleset_fd)
351
+
352
+
353
+ def _seccomp() -> int:
354
+ """Install the filter and return its user-notification listener."""
355
+
356
+ audit_arch, socket_syscall, fcntl_syscall, seccomp_syscall, denied = _architecture()
357
+ instructions: list[tuple[int, int, int, int]] = [
358
+ (BPF_LD_W_ABS, 0, 0, 4),
359
+ (BPF_JMP_JEQ_K, 1, 0, audit_arch),
360
+ (BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
361
+ (BPF_LD_W_ABS, 0, 0, 0),
362
+ ]
363
+ if audit_arch == 0xC000003E:
364
+ instructions.extend(
365
+ [
366
+ (BPF_JMP_JSET_K, 0, 1, 0x40000000),
367
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
368
+ ]
369
+ )
370
+ # Force clone3 callers onto the inspectable clone/fork fallback, then deny
371
+ # only process-style clone(SIGCHLD). Thread creation has a zero exit-signal
372
+ # byte and remains available to ASGI runtimes.
373
+ clone_syscall = 56 if audit_arch == 0xC000003E else 220
374
+ instructions.extend(
375
+ [
376
+ (BPF_JMP_JEQ_K, 0, 1, 435),
377
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.ENOSYS),
378
+ (BPF_LD_W_ABS, 0, 0, 0),
379
+ (BPF_JMP_JEQ_K, 0, 4, clone_syscall),
380
+ (BPF_LD_W_ABS, 0, 0, 16),
381
+ (BPF_ALU_AND_K, 0, 0, 0xFF),
382
+ (BPF_JMP_JEQ_K, 0, 1, signal.SIGCHLD),
383
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
384
+ (BPF_LD_W_ABS, 0, 0, 0),
385
+ ]
386
+ )
387
+ for number in denied:
388
+ instructions.extend(
389
+ [
390
+ (BPF_JMP_JEQ_K, 0, 1, number),
391
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
392
+ ]
393
+ )
394
+ # Classic and OFD byte-range locks are executed by the trusted broker.
395
+ # The tracee is never continued after a pathname/fd check: another tracee
396
+ # thread could otherwise replace the descriptor between check and use.
397
+ brokered_fcntl_commands = (5, 6, 7, 36, 37, 38)
398
+ instructions.extend(
399
+ [
400
+ (
401
+ BPF_JMP_JEQ_K,
402
+ 0,
403
+ 2 * len(brokered_fcntl_commands) + 2,
404
+ fcntl_syscall,
405
+ ),
406
+ (BPF_LD_W_ABS, 0, 0, 24),
407
+ ]
408
+ )
409
+ for command in brokered_fcntl_commands:
410
+ instructions.extend(
411
+ [
412
+ (BPF_JMP_JEQ_K, 0, 1, command),
413
+ (BPF_RET_K, 0, 0, SECCOMP_RET_USER_NOTIF),
414
+ ]
415
+ )
416
+ instructions.append((BPF_LD_W_ABS, 0, 0, 0))
417
+ # socket(domain, type, protocol): permit only IPv4/IPv6 SOCK_STREAM.
418
+ instructions.extend(
419
+ [
420
+ (BPF_JMP_JEQ_K, 0, 8, socket_syscall),
421
+ (BPF_LD_W_ABS, 0, 0, 16),
422
+ (BPF_JMP_JEQ_K, 2, 0, 2),
423
+ (BPF_JMP_JEQ_K, 1, 0, 10),
424
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
425
+ (BPF_LD_W_ABS, 0, 0, 24),
426
+ (BPF_ALU_AND_K, 0, 0, 0xF),
427
+ (BPF_JMP_JEQ_K, 1, 0, 1),
428
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ERRNO | errno.EPERM),
429
+ (BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
430
+ ]
431
+ )
432
+ filters = (_SockFilter * len(instructions))(
433
+ *(_SockFilter(*instruction) for instruction in instructions)
434
+ )
435
+ program = _SockFprog(len(instructions), filters)
436
+ libc = ctypes.CDLL(None, use_errno=True)
437
+ listener = int(
438
+ libc.syscall(
439
+ seccomp_syscall,
440
+ SECCOMP_SET_MODE_FILTER,
441
+ SECCOMP_FILTER_FLAG_NEW_LISTENER,
442
+ ctypes.byref(program),
443
+ )
444
+ )
445
+ if listener < 0:
446
+ raise OSError(ctypes.get_errno(), "cannot install candidate seccomp filter")
447
+ return listener
448
+
449
+
450
+ def _send_fd(channel: socket.socket, descriptor: int) -> None:
451
+ descriptors = array.array("i", [descriptor])
452
+ channel.sendmsg(
453
+ [b"L"],
454
+ [(socket.SOL_SOCKET, socket.SCM_RIGHTS, descriptors.tobytes())],
455
+ )
456
+
457
+
458
+ def _receive_fd(channel: socket.socket) -> int:
459
+ descriptors = array.array("i")
460
+ message, ancillary, _flags, _address = channel.recvmsg(
461
+ 1, socket.CMSG_SPACE(descriptors.itemsize)
462
+ )
463
+ if message != b"L":
464
+ raise OSError(errno.EIO, "candidate sandbox listener was not delivered")
465
+ for level, kind, payload in ancillary:
466
+ if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
467
+ descriptors.frombytes(payload[: descriptors.itemsize])
468
+ return int(descriptors[0])
469
+ raise OSError(errno.EIO, "candidate sandbox listener fd is missing")
470
+
471
+
472
+ def _tracee_process_id(thread_id: int) -> int:
473
+ try:
474
+ for line in Path(f"/proc/{thread_id}/status").read_text().splitlines():
475
+ if line.startswith("Tgid:"):
476
+ return int(line.partition(":")[2].strip())
477
+ except (OSError, ValueError):
478
+ pass
479
+ raise OSError(errno.ESRCH, "cannot identify candidate process")
480
+
481
+
482
+ def _capture_worker_file(pid: int, descriptor: int, data: Path) -> int:
483
+ """Atomically capture a regular data-dir inode from a tracee descriptor."""
484
+
485
+ captured = os.open(f"/proc/{pid}/fd/{descriptor}", os.O_RDWR | os.O_CLOEXEC)
486
+ try:
487
+ metadata = os.fstat(captured)
488
+ if not stat.S_ISREG(metadata.st_mode):
489
+ raise OSError(errno.EPERM, "candidate locks require a regular file")
490
+ target_text = os.readlink(f"/proc/self/fd/{captured}")
491
+ if target_text.endswith(" (deleted)"):
492
+ target_text = target_text[: -len(" (deleted)")]
493
+ target = Path(target_text).resolve()
494
+ if target != data and data not in target.parents:
495
+ raise OSError(errno.EPERM, "candidate lock target is outside data dir")
496
+ return captured
497
+ except BaseException:
498
+ os.close(captured)
499
+ raise
500
+
501
+
502
+ def _read_tracee(pid: int, address: int, size: int) -> bytes:
503
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_RDONLY | os.O_CLOEXEC)
504
+ try:
505
+ value = os.pread(descriptor, size, address)
506
+ finally:
507
+ os.close(descriptor)
508
+ if len(value) != size:
509
+ raise OSError(errno.EFAULT, "candidate fcntl argument is unreadable")
510
+ return value
511
+
512
+
513
+ def _write_tracee(pid: int, address: int, value: bytes) -> None:
514
+ descriptor = os.open(f"/proc/{pid}/mem", os.O_WRONLY | os.O_CLOEXEC)
515
+ try:
516
+ written = os.pwrite(descriptor, value, address)
517
+ finally:
518
+ os.close(descriptor)
519
+ if written != len(value):
520
+ raise OSError(errno.EFAULT, "candidate fcntl result is unwritable")
521
+
522
+
523
+ def _prune_closed_lock_files(
524
+ process_id: int,
525
+ locked_files: dict[tuple[int, int, int], int],
526
+ ) -> None:
527
+ """Release broker descriptors once the tracee has closed their inode.
528
+
529
+ SQLite creates and removes WAL/SHM files as short-lived connections come
530
+ and go. Keeping one broker descriptor for every historical inode pins both
531
+ deleted files and file descriptors until process exit, eventually turning
532
+ ordinary repeated requests into ``SQLITE_IOERR`` under ``RLIMIT_NOFILE``.
533
+ An OFD lock is no longer useful after the tracee has closed every descriptor
534
+ for that inode, so prune it before brokering the next lock operation.
535
+ """
536
+
537
+ open_inodes: set[tuple[int, int]] = set()
538
+ try:
539
+ entries = list(Path(f"/proc/{process_id}/fd").iterdir())
540
+ except OSError:
541
+ return
542
+ for entry in entries:
543
+ try:
544
+ metadata = entry.stat()
545
+ except OSError:
546
+ continue
547
+ open_inodes.add((metadata.st_dev, metadata.st_ino))
548
+ for key, descriptor in list(locked_files.items()):
549
+ owner, device, inode = key
550
+ if owner == process_id and (device, inode) not in open_inodes:
551
+ os.close(descriptor)
552
+ del locked_files[key]
553
+
554
+
555
+ def _broker_fcntl(
556
+ pid: int,
557
+ descriptor: int,
558
+ command: int,
559
+ argument: int,
560
+ data: Path,
561
+ locked_files: dict[tuple[int, int, int], int],
562
+ ) -> int:
563
+ """Execute a byte-range lock without continuing the untrusted syscall."""
564
+
565
+ process_id = _tracee_process_id(pid)
566
+ _prune_closed_lock_files(process_id, locked_files)
567
+ captured = _capture_worker_file(pid, descriptor, data)
568
+ metadata = os.fstat(captured)
569
+ key = (process_id, metadata.st_dev, metadata.st_ino)
570
+ broker_descriptor = locked_files.get(key)
571
+ if broker_descriptor is None:
572
+ locked_files[key] = captured
573
+ broker_descriptor = captured
574
+ else:
575
+ os.close(captured)
576
+
577
+ flock_value = bytearray(_read_tracee(pid, argument, 32))
578
+ # Linux requires l_pid to be zero for OFD lock operations. Classic
579
+ # F_SETLK callers do not own that output-only field, so normalize it when
580
+ # translating the request.
581
+ flock_value[24:28] = b"\0\0\0\0"
582
+ translations = {
583
+ 5: 36, # F_GETLK -> F_OFD_GETLK
584
+ 6: 37, # F_SETLK -> F_OFD_SETLK
585
+ 7: 37, # F_SETLKW stays fail-fast so the broker cannot deadlock.
586
+ 36: 36,
587
+ 37: 37,
588
+ 38: 37,
589
+ }
590
+ result = fcntl.fcntl(broker_descriptor, translations[command], bytes(flock_value))
591
+ if command in {5, 36}:
592
+ if not isinstance(result, bytes):
593
+ raise OSError(errno.EIO, "candidate lock query returned no structure")
594
+ _write_tracee(pid, argument, result.ljust(32, b"\0")[:32])
595
+ return 0
596
+
597
+
598
+ def _lock_broker(listener: int, data: Path) -> None:
599
+ locked_files: dict[tuple[int, int, int], int] = {}
600
+ try:
601
+ while True:
602
+ request = bytearray(_SECCOMP_NOTIF_SIZE)
603
+ try:
604
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_RECV, request, True)
605
+ except OSError as exc:
606
+ if exc.errno in {errno.EINTR, errno.ENOENT, errno.EBADF}:
607
+ if exc.errno == errno.EINTR:
608
+ continue
609
+ return
610
+ raise
611
+ unpacked = struct.unpack(_SECCOMP_NOTIF_FORMAT, request)
612
+ identifier, pid = int(unpacked[0]), int(unpacked[1])
613
+ try:
614
+ value = _broker_fcntl(
615
+ pid,
616
+ int(unpacked[6]),
617
+ int(unpacked[7]),
618
+ int(unpacked[8]),
619
+ data,
620
+ locked_files,
621
+ )
622
+ error = 0
623
+ except OSError as exc:
624
+ value = 0
625
+ error = -(exc.errno or errno.EPERM)
626
+ response = bytearray(
627
+ struct.pack(_SECCOMP_RESP_FORMAT, identifier, value, error, 0)
628
+ )
629
+ try:
630
+ fcntl.ioctl(listener, _SECCOMP_IOCTL_NOTIF_SEND, response, True)
631
+ except OSError as exc:
632
+ if exc.errno != errno.ENOENT:
633
+ raise
634
+ finally:
635
+ for descriptor in locked_files.values():
636
+ os.close(descriptor)
637
+
638
+
639
+ def _drop_credentials(uid: int | None, gid: int | None) -> None:
640
+ """Irreversibly adopt the requested worker identity, when configured."""
641
+
642
+ if uid is None or gid is None:
643
+ return
644
+ os.setgroups([])
645
+ os.setgid(gid)
646
+ os.setuid(uid)
647
+ if os.geteuid() != uid or os.getegid() != gid or os.getgroups():
648
+ raise OSError(errno.EPERM, "worker credential drop did not take effect")
649
+
650
+
651
+ def _kill_and_reap(child_pid: int) -> None:
652
+ try:
653
+ os.kill(child_pid, signal.SIGKILL)
654
+ except ProcessLookupError:
655
+ pass
656
+ try:
657
+ os.waitpid(child_pid, 0)
658
+ except ChildProcessError:
659
+ pass
660
+
661
+
662
+ def sandbox_exec(
663
+ command: Sequence[str],
664
+ *,
665
+ root: Path,
666
+ data: Path,
667
+ bind_port: int,
668
+ connect_ports: set[int],
669
+ uid: int | None,
670
+ gid: int | None,
671
+ file_size_limit_bytes: int | None,
672
+ read_paths: Sequence[Path] = (),
673
+ broker_tid_fd: int | None = None,
674
+ control_fd: int | None = None,
675
+ ) -> None:
676
+ root = root.resolve(strict=True)
677
+ data = data.resolve(strict=True)
678
+ parent_channel, child_channel = socket.socketpair()
679
+ child_pid = os.fork()
680
+ if child_pid == 0:
681
+ parent_channel.close()
682
+ if control_fd is not None:
683
+ os.close(control_fd)
684
+ if broker_tid_fd is not None:
685
+ os.close(broker_tid_fd)
686
+ stage = "landlock"
687
+ try:
688
+ _landlock(root, data, bind_port, connect_ports, read_paths)
689
+ stage = "resource limits"
690
+ if file_size_limit_bytes is not None:
691
+ resource.setrlimit(
692
+ resource.RLIMIT_FSIZE,
693
+ (file_size_limit_bytes, file_size_limit_bytes),
694
+ )
695
+ if uid is not None and gid is not None:
696
+ stage = "credential drop"
697
+ _drop_credentials(uid, gid)
698
+ stage = "lock broker access"
699
+ libc = ctypes.CDLL(None, use_errno=True)
700
+ if libc.prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0:
701
+ raise OSError(ctypes.get_errno(), "cannot enable lock broker access")
702
+ stage = "seccomp"
703
+ listener = _seccomp()
704
+ stage = "listener handoff"
705
+ _send_fd(child_channel, listener)
706
+ os.close(listener)
707
+ child_channel.close()
708
+ stage = "candidate cwd"
709
+ os.chdir(root)
710
+ stage = "candidate exec"
711
+ os.execv(command[0], list(command))
712
+ except BaseException as exc:
713
+ message = f"candidate sandbox setup failed during {stage}: {exc}\n".encode(
714
+ "utf-8", "replace"
715
+ )
716
+ try:
717
+ os.write(2, message)
718
+ except OSError:
719
+ pass
720
+ os._exit(126)
721
+
722
+ child_channel.close()
723
+ try:
724
+ listener = _receive_fd(parent_channel)
725
+ except BaseException:
726
+ _kill_and_reap(child_pid)
727
+ raise
728
+ finally:
729
+ parent_channel.close()
730
+ try:
731
+ _drop_credentials(uid, gid)
732
+ except BaseException:
733
+ os.close(listener)
734
+ _kill_and_reap(child_pid)
735
+ raise
736
+ broker_errors: list[BaseException] = []
737
+ if control_fd is not None:
738
+ os.set_blocking(control_fd, False)
739
+
740
+ def broker() -> None:
741
+ try:
742
+ _lock_broker(listener, data)
743
+ except BaseException as exc:
744
+ broker_errors.append(exc)
745
+
746
+ broker_thread = threading.Thread(target=broker, daemon=True)
747
+ broker_thread.start()
748
+ if broker_tid_fd is not None:
749
+ try:
750
+ native_id = broker_thread.native_id
751
+ if native_id is None:
752
+ raise OSError(errno.EIO, "lock broker thread has no native id")
753
+ os.write(
754
+ broker_tid_fd,
755
+ f"{native_id} {child_pid}\n".encode("ascii"),
756
+ )
757
+ except BaseException:
758
+ os.close(listener)
759
+ _kill_and_reap(child_pid)
760
+ broker_thread.join(timeout=1)
761
+ if control_fd is not None:
762
+ os.close(control_fd)
763
+ raise
764
+ finally:
765
+ os.close(broker_tid_fd)
766
+ status = 0
767
+ while True:
768
+ if control_fd is not None:
769
+ try:
770
+ requested = os.read(control_fd, 4096)
771
+ except (BlockingIOError, OSError):
772
+ requested = b""
773
+ for marker in requested:
774
+ requested_signal = {
775
+ ord("T"): signal.SIGTERM,
776
+ ord("K"): signal.SIGKILL,
777
+ }.get(marker)
778
+ if requested_signal is not None:
779
+ try:
780
+ os.kill(child_pid, requested_signal)
781
+ except ProcessLookupError:
782
+ pass
783
+ waited, status = os.waitpid(child_pid, os.WNOHANG)
784
+ if waited == child_pid:
785
+ break
786
+ if broker_errors:
787
+ os.kill(child_pid, signal.SIGKILL)
788
+ _waited, status = os.waitpid(child_pid, 0)
789
+ break
790
+ time.sleep(0.01)
791
+ if control_fd is not None:
792
+ os.close(control_fd)
793
+ os.close(listener)
794
+ broker_thread.join(timeout=1)
795
+ if broker_errors:
796
+ raise OSError(errno.EIO, "candidate lock broker failed") from broker_errors[0]
797
+ # The trusted launcher/broker completed normally. Candidate business exit
798
+ # status is observed through readiness/lifecycle, while a nonzero launcher
799
+ # status remains reserved for audit infrastructure failure.
800
+ os._exit(0)
801
+
802
+
803
+ def main(argv: Sequence[str] | None = None) -> int:
804
+ parser = argparse.ArgumentParser()
805
+ parser.add_argument("--root", type=Path, required=True)
806
+ parser.add_argument("--data", type=Path, required=True)
807
+ parser.add_argument("--bind-port", type=int, required=True)
808
+ parser.add_argument("--connect-port", type=int, action="append", default=[])
809
+ parser.add_argument("--uid", type=int)
810
+ parser.add_argument("--gid", type=int)
811
+ parser.add_argument("--file-size-limit-bytes", type=int)
812
+ parser.add_argument("--read-path", type=Path, action="append", default=[])
813
+ parser.add_argument("--broker-tid-fd", type=int)
814
+ parser.add_argument("--control-fd", type=int)
815
+ parser.add_argument("command", nargs=argparse.REMAINDER)
816
+ arguments = parser.parse_args(argv)
817
+ command = arguments.command
818
+ if command[:1] == ["--"]:
819
+ command = command[1:]
820
+ if not command:
821
+ parser.error("candidate command is required")
822
+ if (arguments.uid is None) != (arguments.gid is None):
823
+ parser.error("uid and gid must be provided together")
824
+ sandbox_exec(
825
+ command,
826
+ root=arguments.root,
827
+ data=arguments.data,
828
+ bind_port=arguments.bind_port,
829
+ connect_ports=set(arguments.connect_port),
830
+ uid=arguments.uid,
831
+ gid=arguments.gid,
832
+ file_size_limit_bytes=arguments.file_size_limit_bytes,
833
+ read_paths=arguments.read_path,
834
+ broker_tid_fd=arguments.broker_tid_fd,
835
+ control_fd=arguments.control_fd,
836
+ )
837
+ return 127
838
+
839
+
840
+ if __name__ == "__main__":
841
+ raise SystemExit(main())
tasks/brooklinen/environment/reference/clone/frontend/templates/_card.html ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro product_card(p) %}
2
+ <article class="product-card">
3
+ <a href="/products/{{ p.handle }}">
4
+ <div class="product-card__media">
5
+ {% if p.badge %}<span class="badge">{{ p.badge }}</span>{% endif %}
6
+ {% if p.card_image %}<img src="{{ p.card_image }}" alt="{{ p.title }}" loading="lazy">{% endif %}
7
+ <button class="quick-view" type="button">Quick View</button>
8
+ </div>
9
+ <h3 class="product-card__title">{{ p.title }}</h3>
10
+ </a>
11
+ <div class="price">
12
+ <span>From:</span>
13
+ {% if p.on_sale %}<span class="price__was">${{ p.price_min|int }}</span><span>${{ '%.0f'|format(p.sale_price) }}</span><span class="price__off">{{ p.discount_pct }}% off</span>
14
+ {% else %}<span>${{ p.price_min|int }}</span>{% endif %}
15
+ </div>
16
+ {% if p.review_count %}<div class="rating">&#9733;&#9733;&#9733;&#9733;&#9733; ({{ '{:,}'.format(p.review_count) }})</div>{% endif %}
17
+ {% if p.swatches %}
18
+ <div class="swatch-row">
19
+ {% for s in p.swatches[:8] %}<span class="swatch" title="{{ s.title }}"{% if s.hex %} style="background:{{ s.hex }}"{% endif %}>{% if not s.hex and s.image %}<img src="{{ s.image }}" alt="{{ s.title }}" loading="lazy">{% endif %}</span>{% endfor %}
20
+ {% if p.swatches|length > 8 %}<span class="rating">+{{ p.swatches|length - 8 }}</span>{% endif %}
21
+ </div>
22
+ {% endif %}
23
+ </article>
24
+ {% endmacro %}
tasks/brooklinen/environment/reference/clone/frontend/templates/account.html ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}{{ heading }} - Brooklinen - Account{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width account-layout">
5
+ <nav class="account-nav">
6
+ {% for l in account_nav %}<a href="{{ l.url }}" class="{% if l.url == request_path %}is-current{% endif %}">{{ l.label }}</a>{% endfor %}
7
+ <form method="post" action="/account/logout"><button class="remove" type="submit" style="padding:10px 0">Sign out</button></form>
8
+ </nav>
9
+ <section>
10
+ <h1 class="display" style="font-size:34px;margin-bottom:20px">{{ heading }}</h1>
11
+ {% if notice %}<div class="flash">{{ notice }}</div>{% endif %}
12
+ {% if view == 'orders' %}
13
+ {% if orders %}
14
+ <table class="orders">
15
+ <thead><tr><th>Order</th><th>Date</th><th>Items</th><th>Total</th><th>Status</th></tr></thead>
16
+ <tbody>{% for o in orders %}<tr><td>{{ o.number }}</td><td>{{ o.placed_at }}</td><td>{{ o.item_count }}</td><td>${{ '%.2f'|format(o.total) }}</td><td>{{ o.status }}</td></tr>{% endfor %}</tbody>
17
+ </table>
18
+ {% else %}
19
+ <p>You haven't placed any orders yet.</p>
20
+ <p><a class="button button--primary" href="/collections/best-sellers">Ready to shop?</a></p>
21
+ {% endif %}
22
+ {% elif view == 'profile' %}
23
+ <table class="orders"><tbody>
24
+ <tr><th>Email</th><td>{{ customer.email }}</td></tr>
25
+ <tr><th>Member since</th><td>{{ customer.created_at }}</td></tr>
26
+ </tbody></table>
27
+ {% elif view == 'rewards' %}
28
+ <p>You have <strong>{{ rewards.points }}</strong> points to redeem.</p>
29
+ <table class="orders"><tbody>
30
+ <tr><td>400 points</td><td>$10 off</td></tr><tr><td>1000 points</td><td>$25 off</td></tr><tr><td>2000 points</td><td>$50 off</td></tr>
31
+ </tbody></table>
32
+ {% elif view == 'wishlist' %}
33
+ <p>Your wishlist is empty.</p>
34
+ {% endif %}
35
+ </section>
36
+ </div>
37
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/base.html ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>{% block title %}Brooklinen{% endblock %}</title>
7
+ <link rel="stylesheet" href="/static/css/site.css">
8
+ </head>
9
+ <body>
10
+ <div class="announcement">
11
+ <button aria-label="Previous slide" type="button">&#8249;</button>
12
+ <span>{{ announcement }}</span>
13
+ <button aria-label="Next slide" type="button">&#8250;</button>
14
+ </div>
15
+
16
+ <header class="site-header">
17
+ <a class="logo" href="/"><img src="/static/assets/page/Best-In-Bed_Lockup_web-only_Blue.svg" alt="Brooklinen" width="100"></a>
18
+ <nav class="site-nav">
19
+ <ul>
20
+ {% for item in main_nav %}
21
+ <li class="site-nav__item">
22
+ <a href="{{ item.url }}" class="{% if item.url == current_nav %}is-current{% endif %}">{{ item.label }}</a>
23
+ {% set panel = nav_panels.get(item.label) %}
24
+ {% if panel %}
25
+ <div class="top-drawer" role="menu" aria-label="{{ item.label }} menu">
26
+ <div class="top-drawer__shipping">{{ nav_free_shipping }}</div>
27
+ <div class="top-drawer__wrapper">
28
+ {% for col in panel.columns %}
29
+ <div class="top-drawer__col top-drawer__col--{{ col.kind }}">
30
+ {% if col.title %}<h3 class="top-drawer__title">{{ col.title }}</h3>{% endif %}
31
+ {% if col.kind == 'promo' %}
32
+ {% for p in col['items'] %}
33
+ <a class="top-drawer__promo" href="{{ p.url }}">
34
+ {% if p.image %}<img src="{{ p.image }}" alt="{{ p.label }}" loading="lazy">{% endif %}
35
+ <strong>{{ p.label }}</strong>
36
+ {% if p.note %}<span>{{ p.note }}</span>{% endif %}
37
+ </a>
38
+ {% endfor %}
39
+ {% else %}
40
+ <ul>
41
+ {% for l in col['items'] %}
42
+ <li>
43
+ <a href="{{ l.url }}">{{ l.label }}</a>
44
+ {% if l.badge %}<em class="top-drawer__badge">{{ l.badge }}</em>{% endif %}
45
+ {% if l.note %}<span class="top-drawer__note">{{ l.note }}</span>{% endif %}
46
+ </li>
47
+ {% endfor %}
48
+ </ul>
49
+ {% endif %}
50
+ </div>
51
+ {% endfor %}
52
+ </div>
53
+ </div>
54
+ {% endif %}
55
+ </li>
56
+ {% endfor %}
57
+ </ul>
58
+ </nav>
59
+ <div class="header-tools">
60
+ <form class="header-search" action="/search" method="get" role="search">
61
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M16.5 16.5 21 21"/></svg>
62
+ <input type="search" name="q" placeholder="Search ..." aria-label="Search" value="{{ q or '' }}">
63
+ </form>
64
+ <a class="icon" href="/account" aria-label="account"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-7 8-7s8 2.6 8 7"/></svg></a>
65
+ <a class="icon" href="/cart" aria-label="cart"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 8h12l-1 12H7L6 8Z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>{% if cart.item_count %}<span class="cart-count">{{ cart.item_count }}</span>{% endif %}</a>
66
+ </div>
67
+ </header>
68
+ {% if show_social_proof %}<div class="social-proof">&#9733;&#9733;&#9733;&#9733;&#9733; 175,000+ 5-Star Reviews | Best in Bed</div>{% endif %}
69
+
70
+ <main>
71
+ {% block content %}{% endblock %}
72
+ </main>
73
+
74
+ <footer class="site-footer">
75
+ <div class="inner">
76
+ {% for col in footer_nav %}
77
+ <div>
78
+ <h3>{{ col.title }}</h3>
79
+ <ul>{% for l in col.links %}<li><a href="{{ l.url }}">{{ l.label }}</a></li>{% endfor %}</ul>
80
+ </div>
81
+ {% endfor %}
82
+ <div class="newsletter">
83
+ <h2>Get on the List</h2>
84
+ <p>Sign up to know when we launch new products.</p>
85
+ <form action="/newsletter" method="post">
86
+ <input type="email" name="email" placeholder="Email" aria-label="Email" required>
87
+ <button type="submit" aria-label="Subscribe">&#8594;</button>
88
+ </form>
89
+ {% if newsletter_message %}<p class="form-note">{{ newsletter_message }}</p>{% endif %}
90
+ </div>
91
+ </div>
92
+ <div class="legal"><div class="inner"><span>&copy; 2026 Brooklinen</span><span>Offline clone for WebsiteBench — not affiliated with Brooklinen.</span></div></div>
93
+ </footer>
94
+
95
+ {% if show_offer_modal %}
96
+ <div class="offer-modal" id="offer-modal">
97
+ <div class="offer-modal__card">
98
+ <form method="post" action="/offer/dismiss"><button class="offer-modal__close" name="choice" value="close" aria-label="Close">&times;</button></form>
99
+ <img src="/static/assets/page/Best-In-Bed_Lockup_web-only_Blue.svg" alt="Brooklinen" width="150" style="margin:0 auto">
100
+ <h2>Hi, want 15% off?</h2>
101
+ <p>Be the first to know about exclusive deals and new product drops!</p>
102
+ <form method="post" action="/offer/dismiss">
103
+ <button class="button button--primary button--block" name="choice" value="signup" type="submit">Sign Up</button>
104
+ <button class="offer-modal__decline" name="choice" value="decline" type="submit">No thanks, I'll pay full price</button>
105
+ </form>
106
+ </div>
107
+ </div>
108
+ {% endif %}
109
+ </body>
110
+ </html>
tasks/brooklinen/environment/reference/clone/frontend/templates/cart.html ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Your Shopping Cart – Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width">
5
+ <h1 class="display" style="font-size:38px;padding:28px 0 6px">Your Cart</h1>
6
+ {% if not cart.lines %}
7
+ <div class="empty-state">
8
+ <p>Your cart is empty</p>
9
+ <p><a class="button button--primary" href="/">Go to Homepage</a> <a class="button button--tertiary" href="/collections/best-sellers">Shop Best Sellers</a></p>
10
+ </div>
11
+ {% else %}
12
+ <div class="cart-layout">
13
+ <div>
14
+ {% for line in cart.lines %}
15
+ <div class="cart-line">
16
+ <a href="/products/{{ line.handle }}">{% if line.image %}<img src="{{ line.image }}" alt="{{ line.title }}">{% endif %}</a>
17
+ <div>
18
+ <a href="/products/{{ line.handle }}"><strong>{{ line.title }}</strong></a>
19
+ <div class="opt">Color: {{ line.option1 }}{% if line.option2 %} / {{ line.option2 }}{% endif %}</div>
20
+ <div class="price" style="margin-top:10px">
21
+ {% if line.on_sale %}<span class="price__was">${{ line.unit_price|int }}</span><span>${{ '%.2f'|format(line.unit_sale_price) }}</span>{% else %}<span>${{ '%.2f'|format(line.unit_price) }}</span>{% endif %}
22
+ </div>
23
+ <form method="post" action="/cart/remove"><input type="hidden" name="variant_id" value="{{ line.variant_id }}"><button class="remove" type="submit">Remove</button></form>
24
+ </div>
25
+ <form method="post" action="/cart/change">
26
+ <input type="hidden" name="variant_id" value="{{ line.variant_id }}">
27
+ <label style="font-size:14px">Qty:
28
+ <select name="quantity" onchange="this.form.submit()">
29
+ {% for n in range(1, 11) %}<option value="{{ n }}" {% if n == line.quantity %}selected{% endif %}>{{ n }}</option>{% endfor %}
30
+ </select></label>
31
+ </form>
32
+ </div>
33
+ {% endfor %}
34
+ </div>
35
+ <aside class="cart-summary">
36
+ <div class="free-ship">
37
+ {% if cart.free_shipping_remaining > 0 %}You're just ${{ '%.2f'|format(cart.free_shipping_remaining) }} away from Free Shipping!{% else %}You've unlocked Free Shipping!{% endif %}
38
+ <div class="progress"><i style="width:{{ cart.free_shipping_pct }}%"></i></div>
39
+ </div>
40
+ {% if cart.savings %}<div class="row" style="color:#417823">You saved ${{ '%.2f'|format(cart.savings) }}!</div>{% endif %}
41
+ <div class="row"><span>Subtotal</span><span>${{ '%.2f'|format(cart.subtotal) }}</span></div>
42
+ <div class="row"><span>Shipping</span><span>{{ cart.shipping_label }}</span></div>
43
+ <div class="row"><span>Taxes</span><span>Calculated at checkout</span></div>
44
+ <div class="row total"><span>Estimated total</span><span>${{ '%.2f'|format(cart.subtotal) }}</span></div>
45
+ <p style="margin-top:20px"><a class="button button--primary button--block" href="/checkout">Checkout</a></p>
46
+ <p class="form-note">Have a promo code? Enter it on the next page.</p>
47
+ </aside>
48
+ </div>
49
+ {% endif %}
50
+ </div>
51
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/checkout.html ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Checkout – Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width form-card">
5
+ <h1>Checkout</h1>
6
+ <p class="form-note">Local sandbox checkout. No real payment is taken and no message leaves this process.</p>
7
+ <form method="post" action="/checkout">
8
+ <label for="email">Email</label>
9
+ <input id="email" name="email" type="email" required value="{{ customer.email if customer else '' }}">
10
+ <label for="scenario">Payment scenario</label>
11
+ <select id="scenario" name="scenario" style="width:100%;padding:13px;border:1px solid #cfc9c3;border-radius:5px">
12
+ {% for s in scenarios %}<option value="{{ s.id }}">{{ s.label }}</option>{% endfor %}
13
+ </select>
14
+ <div class="row" style="display:flex;justify-content:space-between;padding:18px 0;color:#283455">
15
+ <span>Order total</span><span>${{ '%.2f'|format(cart.subtotal) }}</span>
16
+ </div>
17
+ <div class="actions"><button class="button button--primary button--block" type="submit">Place order</button></div>
18
+ </form>
19
+ </div>
20
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/collection.html ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% from "_card.html" import product_card %}
3
+ {% block title %}{{ collection.title }} | Brooklinen{% endblock %}
4
+ {% block content %}
5
+ <div class="page-width breadcrumbs"><a href="/">Home</a> / {{ collection.title }}</div>
6
+ <div class="page-width collection-title">
7
+ <h1 class="display">{{ collection.title }}</h1>
8
+ {% if lede %}<p class="collection-lede">{{ lede }}</p>{% endif %}
9
+ </div>
10
+ {% if fabrics %}
11
+ {# Source renders this as an edge-bleeding carousel: 244x122 tiles on a 268px pitch,
12
+ first full tile at the page gutter, neighbours clipped at both edges. #}
13
+ <section class="fabric-carousel" aria-label="Shop by fabric">
14
+ <div class="fabric-carousel__track">
15
+ <a class="cat-tile cat-tile--fabric" href="{{ fabrics[-1].url }}" aria-hidden="true" tabindex="-1">{% if fabrics[-1].image %}<img src="{{ fabrics[-1].image }}" alt="">{% endif %}<span>{{ fabrics[-1].label }}{% if fabrics[-1].note %}<em>{{ fabrics[-1].note }}</em>{% endif %}</span></a>
16
+ {% for f in fabrics %}
17
+ <a class="cat-tile cat-tile--fabric" href="{{ f.url }}">{% if f.image %}<img src="{{ f.image }}" alt="{{ f.label }}">{% endif %}<span>{{ f.label }}{% if f.note %}<em>{{ f.note }}</em>{% endif %}</span></a>
18
+ {% endfor %}
19
+ <a class="cat-tile cat-tile--fabric" href="{{ fabrics[0].url }}" aria-hidden="true" tabindex="-1">{% if fabrics[0].image %}<img src="{{ fabrics[0].image }}" alt="">{% endif %}<span>{{ fabrics[0].label }}{% if fabrics[0].note %}<em>{{ fabrics[0].note }}</em>{% endif %}</span></a>
20
+ </div>
21
+ </section>
22
+ {% endif %}
23
+ <div class="page-width collection">
24
+ <form class="facets" method="get" id="facets">
25
+ <div class="collection-head" style="margin-bottom:12px">
26
+ <h2 style="margin:0"><span class="facets__icon" aria-hidden="true">&#8942;</span> Filters</h2>
27
+ <a class="clear" href="/collections/{{ collection.handle }}">Clear All Filters</a>
28
+ </div>
29
+ {% for facet in facets %}
30
+ <details class="facet" {% if loop.index <= 3 or facet.options | selectattr('checked') | list %}open{% endif %}>
31
+ <summary>{{ facet.label }}</summary>
32
+ <div class="facet__values">
33
+ {% for v in facet.options %}
34
+ <label><input type="checkbox" name="{{ facet.name }}" value="{{ v.value }}" {% if v.checked %}checked{% endif %} onchange="document.getElementById('facets').submit()"> <span>{{ v.value }}</span></label>
35
+ {% endfor %}
36
+ </div>
37
+ </details>
38
+ {% endfor %}
39
+ </form>
40
+ <div>
41
+ <div class="collection-head">
42
+ <span class="count">{{ total }} products</span>
43
+ </div>
44
+ <div class="product-grid">{% for p in products %}{{ product_card(p) }}{% endfor %}</div>
45
+ {% if has_more %}
46
+ <div class="load-more"><a class="button button--tertiary" href="{{ more_url }}">Show More</a></div>
47
+ {% endif %}
48
+ </div>
49
+ </div>
50
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/content.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}{{ page.title }} | Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width breadcrumbs"><a href="/">Home</a> / {{ page.title }}</div>
5
+ <div class="page-width" style="padding-bottom:70px">
6
+ <h1 class="display" style="font-size:42px;margin-bottom:20px">{{ page.title }}</h1>
7
+ <div class="seo-block">{{ page.body|safe }}</div>
8
+ </div>
9
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/home.html ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% from "_card.html" import product_card %}
3
+ {% block title %}Luxury Bedding, Sheets & Comforters Online | Brooklinen{% endblock %}
4
+ {% block content %}
5
+ <section class="hero">
6
+ {% if hero.image %}<img src="{{ hero.image }}" alt="">{% endif %}
7
+ <div class="hero__inner">
8
+ <h1>{% if hero.heading_lockup %}<img class="hero__lockup" src="{{ hero.heading_lockup }}" alt="{{ hero.heading }}">{% else %}{{ hero.heading }}{% endif %}</h1>
9
+ <p>{{ hero.body }}</p>
10
+ <div class="hero__cta">
11
+ <a class="button" href="{{ hero.url }}">{{ hero.cta }}</a>
12
+ <a class="button" href="{{ hero.secondary_url }}">{{ hero.secondary_cta }}</a>
13
+ </div>
14
+ </div>
15
+ </section>
16
+
17
+ <section class="section carousel-module">
18
+ <div class="page-width"><h2 class="h-section">{{ collection_module.title }}</h2></div>
19
+ <div class="page-width"><div class="product-grid">{% for p in collection_module.products %}{{ product_card(p) }}{% endfor %}</div></div>
20
+ </section>
21
+
22
+ <section class="section page-width">
23
+ <h2 class="h-section">Shop by Category</h2>
24
+ <div class="cat-strip">
25
+ {% for c in categories %}
26
+ <a class="cat-tile" href="{{ c.url }}">
27
+ {% if c.image %}<img src="{{ c.image }}" alt="{{ c.label }}">{% endif %}
28
+ {% if c.badge %}<img class="cat-tile__badge" src="{{ c.badge }}" alt="">{% endif %}
29
+ <span>{{ c.label }}</span>
30
+ </a>
31
+ {% endfor %}
32
+ </div>
33
+ </section>
34
+
35
+ <section class="hero hero--secondary">
36
+ {% if new_hero.image %}<img src="{{ new_hero.image }}" alt="">{% endif %}
37
+ <div class="hero__inner">
38
+ <h1 class="hero__plain">{{ new_hero.heading }}</h1>
39
+ <p>{{ new_hero.body }}</p>
40
+ <div class="hero__cta"><a class="button" href="{{ new_hero.url }}">{{ new_hero.cta }}</a></div>
41
+ </div>
42
+ </section>
43
+
44
+ <section class="section carousel-module">
45
+ <div class="page-width"><h2 class="h-section">{{ new_arrivals_module.title }}</h2></div>
46
+ <div class="page-width"><div class="product-grid">{% for p in new_arrivals_module.products %}{{ product_card(p) }}{% endfor %}</div></div>
47
+ </section>
48
+
49
+ <section class="duo-shop">
50
+ <a class="duo-shop__feature" href="{{ duo.url }}">
51
+ {% if duo.image %}<img src="{{ duo.image }}" alt="">{% endif %}
52
+ <div class="duo-shop__copy"><p>{{ duo.heading }}</p><span class="button button--tertiary">{{ duo.cta }}</span></div>
53
+ </a>
54
+ <div class="duo-shop__grid">
55
+ {% for p in duo.products %}
56
+ <a class="duo-shop__tile" href="/products/{{ p.handle }}">
57
+ {% if p.card_image %}<img src="{{ p.card_image }}" alt="{{ p.title }}">{% endif %}
58
+ <strong>{{ p.title }}</strong>
59
+ <span class="button button--tertiary">Shop Now</span>
60
+ </a>
61
+ {% endfor %}
62
+ </div>
63
+ </section>
64
+
65
+ <section class="page-width">
66
+ <h2 class="display" style="font-size:45px;text-align:center;padding-top:40px">Why Brooklinen?</h2>
67
+ <div class="value-props">
68
+ <div><h3>Premium Materials &amp; Exclusive Styles</h3><p>Only the best&mdash;that&rsquo;s what you deserve.</p></div>
69
+ <div><h3>365-Day Happiness Guarantee</h3><p>It&rsquo;ll be love at first sleep (or bath).</p></div>
70
+ <div><h3>Fast, Free Shipping</h3><p>We&rsquo;re New Yorkers, we move quick.</p></div>
71
+ </div>
72
+ </section>
73
+
74
+ <section class="page-width reviews">
75
+ <div>
76
+ <h2 class="display" style="font-size:45px;line-height:1.1">175k+ 5-Star Reviews<br>Don't Lie</h2>
77
+ <p><a class="button button--tertiary" href="/pages/reviews">Read Our Reviews</a></p>
78
+ </div>
79
+ <div class="review-cards">
80
+ {% for r in reviews %}
81
+ <div class="review-card"><h4>{{ r.headline }}</h4><p>&ldquo;{{ r.body }}&rdquo;</p><div class="who">{{ r.who }}</div></div>
82
+ {% endfor %}
83
+ </div>
84
+ </section>
85
+
86
+ <section class="section page-width">
87
+ <div class="spotlight">
88
+ {% for s in spotlight %}
89
+ <figure>
90
+ <a href="{{ s.url }}">{% if s.image %}<img src="{{ s.image }}" alt="{{ s.label }}">{% endif %}</a>
91
+ <figcaption>{{ s.label }}</figcaption>
92
+ <a class="button button--tertiary" href="{{ s.url }}">Shop Now</a>
93
+ </figure>
94
+ {% endfor %}
95
+ </div>
96
+ </section>
97
+
98
+ <section class="press page-width">
99
+ <div class="press__head">
100
+ <h2 class="h-section" style="margin:0">{{ press.heading }}</h2>
101
+ <a class="button button--tertiary press__cta" href="{{ press.url }}">{{ press.cta }}</a>
102
+ </div>
103
+ <div class="press__logos">
104
+ {% for logo in press.logos %}<img src="{{ logo }}" alt="" loading="lazy">{% endfor %}
105
+ </div>
106
+ </section>
107
+
108
+ <section class="stores page-width">
109
+ <h2 class="display">{{ stores.heading }}</h2>
110
+ <p>{{ stores.body }}</p>
111
+ <a href="{{ stores.url }}">{{ stores.cta }}</a>
112
+ </section>
113
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/landing.html ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% from "_card.html" import product_card %}
3
+ {% block title %}{{ page.seo_title }}{% endblock %}
4
+ {% block content %}
5
+ <div class="page-width breadcrumbs"><a href="/">Home</a> / {{ page.title }}</div>
6
+ <div class="page-width landing-head">
7
+ <h1 class="display">{{ page.title }}</h1>
8
+ {% if page.lede %}<p class="landing-lede">{{ page.lede }}</p>{% endif %}
9
+ </div>
10
+
11
+ {% if page.jump_to %}
12
+ <nav class="page-navigation page-width" aria-label="Jump to a section">
13
+ <span class="page-navigation__label">Jump to:</span>
14
+ {% for row in page.rows %}{% if row.id %}
15
+ <a class="button button--tertiary page-navigation__pill" href="#{{ page.slug }}-{{ row.id }}">{{ row.title }}</a>
16
+ {% endif %}{% endfor %}
17
+ </nav>
18
+ {% endif %}
19
+
20
+ {% if page.fabrics and not page.jump_to %}
21
+ <section class="page-width section">
22
+ <h2 class="h-section">{{ page.fabric_heading }}</h2>
23
+ <div class="cat-strip cat-strip--fabric">
24
+ {% for f in page.fabrics %}
25
+ <a class="cat-tile cat-tile--fabric" href="{{ f.url }}">{% if f.image %}<img src="{{ f.image }}" alt="{{ f.label }}">{% endif %}<span>{{ f.label }}{% if f.note %}<em>{{ f.note }}</em>{% endif %}</span></a>
26
+ {% endfor %}
27
+ </div>
28
+ </section>
29
+ {% endif %}
30
+
31
+ {% for row in page.rows %}
32
+ {% if row.kind == 'promo-band' %}
33
+ <section class="promo-band page-width">
34
+ <h2>{{ row.title }}</h2>
35
+ <p>{{ row.body }}</p>
36
+ <a class="button button--tertiary" href="{{ row.url }}">{{ row.cta }}</a>
37
+ </section>
38
+ {% elif row.kind == 'fabric-strip' %}
39
+ <section class="page-width section">
40
+ <h2 class="h-section">{{ row.title }}</h2>
41
+ <div class="cat-strip cat-strip--fabric">
42
+ {% for f in page.fabrics %}
43
+ <a class="cat-tile cat-tile--fabric" href="{{ f.url }}">{% if f.image %}<img src="{{ f.image }}" alt="{{ f.label }}">{% endif %}<span>{{ f.label }}{% if f.note %}<em>{{ f.note }}</em>{% endif %}</span></a>
44
+ {% endfor %}
45
+ </div>
46
+ </section>
47
+ {% else %}
48
+ <section class="page-width section" {% if row.id %}id="{{ page.slug }}-{{ row.id }}"{% endif %}>
49
+ <div class="collection-head{% if page.row_heading_align == 'center' %} collection-head--centered{% endif %}">
50
+ <div>
51
+ <h2 class="h-section" style="margin:0">{{ row.title }}</h2>
52
+ {% if row.includes %}<p class="row-includes">{{ row.includes }}</p>{% endif %}
53
+ </div>
54
+ {% if row.url %}<a class="rating" href="{{ row.url }}" style="text-decoration:underline">Shop All</a>{% endif %}
55
+ </div>
56
+ <div class="product-grid">{% for p in row.products %}{{ product_card(p) }}{% endfor %}</div>
57
+ </section>
58
+ {% endif %}
59
+ {% endfor %}
60
+
61
+ {% if page.spotlight %}
62
+ <section class="section page-width">
63
+ <h2 class="h-section">{{ page.spotlight_title }}</h2>
64
+ <div class="spotlight spotlight--pair">
65
+ {% for s in page.spotlight %}
66
+ <figure>
67
+ <a href="{{ s.url }}">{% if s.image %}<img src="{{ s.image }}" alt="{{ s.label }}">{% endif %}</a>
68
+ <figcaption>{{ s.label }}</figcaption>
69
+ <a class="button button--tertiary" href="{{ s.url }}">Shop Now</a>
70
+ </figure>
71
+ {% endfor %}
72
+ </div>
73
+ </section>
74
+ {% endif %}
75
+
76
+ {% if page.seo_html %}
77
+ <section class="page-width seo-block"><h2>{{ page.seo_heading }}</h2>{{ page.seo_html|safe }}</section>
78
+ {% endif %}
79
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/login.html ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Sign in – Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width form-card">
5
+ <h1>Welcome back</h1>
6
+ <p class="form-note">Sign in to see your orders, rewards and wishlist.</p>
7
+ {% if error %}<div class="flash flash--error">{{ error }}</div>{% endif %}
8
+ {% if notice %}<div class="flash">{{ notice }}</div>{% endif %}
9
+ <form method="post" action="/account/login">
10
+ <label for="email">Email</label>
11
+ <input id="email" name="email" type="email" required autocomplete="username" value="{{ email or '' }}">
12
+ <label for="password">Password</label>
13
+ <input id="password" name="password" type="password" required autocomplete="current-password">
14
+ <div class="actions"><button class="button button--primary button--block" type="submit">Sign In</button></div>
15
+ </form>
16
+ <p class="form-note">New here? <a href="/account/register" style="text-decoration:underline">Create an account</a>.</p>
17
+ <p class="form-note">Forgot your password? <a href="/account/reset" style="text-decoration:underline">Reset it</a>.</p>
18
+ </div>
19
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/notfound.html ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Page not found | Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width empty-state">
5
+ <h1 class="display" style="font-size:44px">We couldn't find that page.</h1>
6
+ <p>The page you're looking for doesn't exist or has moved.</p>
7
+ <p><a class="button button--primary" href="/">Go to Homepage</a> <a class="button button--tertiary" href="/collections/best-sellers">Shop Best Sellers</a></p>
8
+ </div>
9
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/order.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Order {{ order.number }} – Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width form-card">
5
+ <h1>{% if order.outcome == 'approved' %}Thank you!{% else %}Payment {{ order.outcome }}{% endif %}</h1>
6
+ {% if order.outcome == 'approved' %}
7
+ <div class="flash">Order {{ order.number }} for ${{ '%.2f'|format(total) }} is confirmed. A confirmation was written to the <a href="/dev/outbox" style="text-decoration:underline">local outbox</a> for {{ email }}.</div>
8
+ <p><a class="button button--primary" href="/account/orders">View your orders</a></p>
9
+ {% else %}
10
+ <div class="flash flash--error">The sandbox payment was {{ order.outcome }}. Your cart was kept so you can try again.</div>
11
+ <p><a class="button button--tertiary" href="/cart">Back to cart</a></p>
12
+ {% endif %}
13
+ </div>
14
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/outbox.html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Local outbox – Brooklinen offline clone{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width section">
5
+ <h1 class="display" style="font-size:32px">Local mail outbox</h1>
6
+ <p class="form-note">Deterministic local sandbox. No mail leaves this process.</p>
7
+ <table class="orders"><thead><tr><th>To</th><th>Subject</th><th>Body</th><th>Status</th></tr></thead>
8
+ <tbody>{% for m in messages %}<tr><td>{{ m.to }}</td><td>{{ m.subject }}</td><td>{{ m.body }}</td><td>{{ m.status }}</td></tr>{% endfor %}</tbody></table>
9
+ </div>
10
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/product.html ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% from "_card.html" import product_card %}
3
+ {% block title %}{{ product.title }} | Brooklinen{% endblock %}
4
+ {% block content %}
5
+ <div class="page-width breadcrumbs">
6
+ <a href="/">Home</a> / <a href="/pages/all-bath">All Bath</a> / {{ product.title }}
7
+ </div>
8
+ <div class="page-width pdp">
9
+ <div class="pdp__gallery">
10
+ <div class="pdp__thumbs">
11
+ {% for img in gallery %}
12
+ <a href="?variant={{ variant.id }}&amp;image={{ loop.index0 }}" class="{% if loop.index0 == image_index %}is-active{% endif %}"><img src="{{ img.thumb }}" alt="{{ product.title }} view {{ loop.index }}"></a>
13
+ {% endfor %}
14
+ </div>
15
+ <div class="pdp__hero">{% if product.badge %}<span class="badge">{{ product.badge }}</span>{% endif %}{% if hero_image %}<img src="{{ hero_image }}" alt="{{ product.title }}">{% endif %}</div>
16
+ </div>
17
+ <div>
18
+ <h1>{{ product.title }}</h1>
19
+ {% if product.lede %}<p class="lede">{{ product.lede }}</p>{% endif %}
20
+ <div class="rating">&#9733;&#9733;&#9733;&#9733;&#9733; ({{ '{:,}'.format(product.review_count) }})</div>
21
+
22
+ <div class="option-label">Color <b>{{ variant.option1 }}</b>{% if variant.color_description %}<span class="desc">, {{ variant.color_description }}</span>{% endif %}</div>
23
+ <div class="swatches">
24
+ {% for v in colors %}
25
+ <a href="?variant={{ v.id }}" title="{{ v.title }}" aria-label="{{ v.title }}" class="{% if v.id == variant.id %}is-selected{% endif %}"{% if v.hex %} style="background:{{ v.hex }}"{% endif %}>{% if not v.hex and v.swatch %}<img src="{{ v.swatch }}" alt="{{ v.title }}">{% endif %}</a>
26
+ {% endfor %}
27
+ </div>
28
+
29
+ {% if sizes %}
30
+ <div class="option-label">Size <b>{{ variant.option2 }}</b></div>
31
+ <div class="swatches">
32
+ {% for s in sizes %}<a href="?variant={{ s.id }}" class="button button--tertiary {% if s.id == variant.id %}is-selected{% endif %}" style="width:auto;height:auto;border-radius:999px;padding:10px 20px">{{ s.label }}</a>{% endfor %}
33
+ </div>
34
+ {% endif %}
35
+
36
+ <div class="price">
37
+ {% if product.on_sale %}<span class="price__was">${{ variant.price|int }}</span><span>${{ '%.2f'|format(variant.sale_price) }}</span><span class="price__off">{{ product.discount_pct }}% off</span>
38
+ {% else %}<span>${{ '%.2f'|format(variant.price) }}</span>{% endif %}
39
+ </div>
40
+
41
+ <form method="post" action="/cart/add">
42
+ <input type="hidden" name="variant_id" value="{{ variant.id }}">
43
+ <button class="button button--primary button--block" type="submit" {% if not variant.available %}disabled{% endif %}>
44
+ {{ 'Add to Cart' if variant.available else 'Sold Out' }}
45
+ </button>
46
+ </form>
47
+ {% if added %}<div class="flash">Added to your cart.</div>{% endif %}
48
+ <div class="social-note">{{ product.social_note }}</div>
49
+
50
+ <div class="accordion">
51
+ {% for section in product.details %}
52
+ <details {% if loop.first %}open{% endif %}><summary>{{ section.title }}</summary><div class="body">{{ section.body|safe }}</div></details>
53
+ {% endfor %}
54
+ </div>
55
+ </div>
56
+ </div>
57
+
58
+ {% if related %}
59
+ <section class="page-width section">
60
+ <h2 class="h-section">You may also like</h2>
61
+ <div class="product-grid product-grid--4">{% for p in related %}{{ product_card(p) }}{% endfor %}</div>
62
+ </section>
63
+ {% endif %}
64
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/register.html ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% block title %}Create account – Brooklinen{% endblock %}
3
+ {% block content %}
4
+ <div class="page-width form-card">
5
+ <h1>Create your account</h1>
6
+ {% if error %}<div class="flash flash--error">{{ error }}</div>{% endif %}
7
+ {% if notice %}<div class="flash">{{ notice }}</div>{% endif %}
8
+ {% if stage == 'verify' %}
9
+ <p class="form-note">We sent a verification code to <strong>{{ email }}</strong>. In this offline clone the code is delivered to the <a href="/dev/outbox" style="text-decoration:underline">local outbox</a>.</p>
10
+ <form method="post" action="/account/register/verify">
11
+ <label for="code">Verification code</label>
12
+ <input id="code" name="code" required inputmode="numeric" autocomplete="one-time-code">
13
+ <div class="actions"><button class="button button--primary button--block" type="submit">Verify and create account</button></div>
14
+ </form>
15
+ {% else %}
16
+ <form method="post" action="/account/register">
17
+ <label for="email">Email</label>
18
+ <input id="email" name="email" type="email" required autocomplete="username">
19
+ <label for="password">Password</label>
20
+ <input id="password" name="password" type="password" required autocomplete="new-password">
21
+ <div class="actions"><button class="button button--primary button--block" type="submit">Create account</button></div>
22
+ </form>
23
+ {% endif %}
24
+ <p class="form-note">Already have an account? <a href="/account/login" style="text-decoration:underline">Sign in</a>.</p>
25
+ </div>
26
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/frontend/templates/search.html ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+ {% from "_card.html" import product_card %}
3
+ {% block title %}Search: {{ total }} results for "{{ q }}"{% endblock %}
4
+ {% block content %}
5
+ <div class="page-width section">
6
+ <h1 class="display" style="font-size:38px">Search results for: &ldquo;{{ q }}&rdquo;</h1>
7
+ <p class="count" style="color:#6b7280">{{ total }} results found</p>
8
+ {% if products %}
9
+ <div class="product-grid product-grid--4" style="margin-top:28px">{% for p in products %}{{ product_card(p) }}{% endfor %}</div>
10
+ {% else %}
11
+ <div class="empty-state"><p>No results found for &ldquo;{{ q }}&rdquo;.</p><p><a class="button button--tertiary" href="/collections/best-sellers">Shop Best Sellers</a></p></div>
12
+ {% endif %}
13
+ </div>
14
+ {% endblock %}
tasks/brooklinen/environment/reference/clone/static/assets/fonts/ToledoSerial-Bold.otf ADDED
Binary file (42.6 kB). View file
 
tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextBold.woff2 ADDED
Binary file (35.6 kB). View file
 
tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextRegular.woff2 ADDED
Binary file (34.5 kB). View file
 
tasks/brooklinen/environment/reference/clone/static/assets/fonts/f__BrandonTextWeb-Italic--360967_8_0.woff2 ADDED
Binary file (33 kB). View file
 
tasks/brooklinen/environment/reference/clone/static/assets/fonts/wf_BrandonTextWeb-Medium--360967_B_0.woff2 ADDED
Binary file (33.2 kB). View file
 
tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9149_x_PDP_WO_f6573af1-b775-4727-a79a-783a72bdeb9d__600x.jpg ADDED

Git LFS Details

  • SHA256: 74a2c9093b2cea11ac7b7c01a355a2844b438e099b408bd4b6c3b895ba256f28
  • Pointer size: 130 Bytes
  • Size of remote file: 86.7 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9170_x_PDP_WO_72702b5e-b89e-427e-bde0-cd7d52897d50__600x.jpg ADDED

Git LFS Details

  • SHA256: 472de36db947073fa7004663c89f2ae26ebb4a8c457e4c65ebab5bf1b06dc64a
  • Pointer size: 131 Bytes
  • Size of remote file: 114 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/012126_BKL_Q1MarchLilos9199_x_PDP_WO_44efe1fe-6aa4-4e29-9d64-2c9c4799640b__600x.jpg ADDED

Git LFS Details

  • SHA256: afc6a372b8d9908cfb0bd6ce7791c04a7497bbb16707770c97deec193a3dea87
  • Pointer size: 130 Bytes
  • Size of remote file: 93 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/1_BKL_20_AltDownTopper_UB_2__400x.jpg ADDED

Git LFS Details

  • SHA256: a057e17d2bcccd67358fc9ce031040de112897bd18ae7d9051f82dc2fcd0aa47
  • Pointer size: 129 Bytes
  • Size of remote file: 5.01 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/1_BKL_20_PillowProtector_UB_2__400x.jpg ADDED

Git LFS Details

  • SHA256: e0700453e3ad3c2f20a86ff1b678e22f5a3c55f9c671f65a631722c39cb7415c
  • Pointer size: 129 Bytes
  • Size of remote file: 4.29 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/250723_WashedClassicOverhead7114x_PDP_WO_2f1a33bd-6c4a-4912-a6aa-03864ea5d29d__600x.jpg ADDED

Git LFS Details

  • SHA256: 96278f243ce898e86cd1818bf6e2a697142f0fef2798a0cc94ce70450625c0c6
  • Pointer size: 130 Bytes
  • Size of remote file: 84.5 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/250723_WashedClassicOverhead7372x_PDP_WO__600x.jpg ADDED

Git LFS Details

  • SHA256: db7633d50ea4f3468d64ccbabdae4aba3f8d4ee985ed8df36e618bbb04e3cd54
  • Pointer size: 130 Bytes
  • Size of remote file: 60.9 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK0654_1__150x.jpg ADDED

Git LFS Details

  • SHA256: b95abb1bebd48ca424cbaafcb6f353863e0bb218c82a88eb645f09e0ba6f4665
  • Pointer size: 129 Bytes
  • Size of remote file: 3.41 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK1064_1__600x.jpg ADDED

Git LFS Details

  • SHA256: 6dd733e145ff64657106aeb19457134c1b56ac30475c639d826d8ea075b8ff21
  • Pointer size: 130 Bytes
  • Size of remote file: 23.2 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK1D2F_1__600x.jpg ADDED

Git LFS Details

  • SHA256: d7d74fc0787d4d3b22492b4cf34318644da65e372a234f763c8552a0645865dd
  • Pointer size: 130 Bytes
  • Size of remote file: 25.2 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK2D69_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 12485361949527100a3f38f601eb48f13fc1dfd55700977bd458533ff75c2606
  • Pointer size: 129 Bytes
  • Size of remote file: 2.49 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK4478_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 52009ea133d1b27fb31580e85a6b6a550f6200326d83f6d1c072f461ab897b2f
  • Pointer size: 129 Bytes
  • Size of remote file: 2.82 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK6EF5_1__600x.jpg ADDED

Git LFS Details

  • SHA256: 0a1d20ddc9edf2a750ce691f49f4fba6ac8d08787aa4c0074b567cf9e04e200e
  • Pointer size: 130 Bytes
  • Size of remote file: 46.3 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK73A3_1__600x.jpg ADDED

Git LFS Details

  • SHA256: fd4fad8a36c4308ab0b9c33457d0a52882b1aed257c2297626624f58590a6f83
  • Pointer size: 130 Bytes
  • Size of remote file: 39.4 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK7885_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 34b5771bb592830f989cecba7343f06e84a11f1c945fa1d906eda7db152af43e
  • Pointer size: 129 Bytes
  • Size of remote file: 1.95 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK8506_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 89406a0f081da4ae6ad2e0e03c75724a7146854b96405011111c91c91e391eb9
  • Pointer size: 129 Bytes
  • Size of remote file: 3.34 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BK9711_1_965df1b0-454d-48dc-812e-5024396583f6__150x.jpg ADDED

Git LFS Details

  • SHA256: b70ae48d94cb359a2eddead9a9c4235e63e924c5a15e3433c420a2d1f38e2e1e
  • Pointer size: 129 Bytes
  • Size of remote file: 2.6 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKA027_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 6e8c9e93bb5d435d00ea3e0a1d4fe260f7c55ea9323e96bf3b63e5801f5c7d4f
  • Pointer size: 129 Bytes
  • Size of remote file: 3.37 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKAD07_1__1000x.jpg ADDED

Git LFS Details

  • SHA256: 47e84052369b8f071126f5ff3200a8622f6900202c8e5c91bae53d73bdfa668a
  • Pointer size: 130 Bytes
  • Size of remote file: 75.6 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKAD07_1__400x.jpg ADDED

Git LFS Details

  • SHA256: e6c1568a56ca36f1062dc9ee8d5b3bfd6769a94df8030c04ad3e0b72d5237475
  • Pointer size: 130 Bytes
  • Size of remote file: 10.1 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKAEA8_1__150x.jpg ADDED

Git LFS Details

  • SHA256: 3afd03dfd9ba66de0ba806267c93c757054597737f688722a5bbb113b13e27ef
  • Pointer size: 129 Bytes
  • Size of remote file: 2.53 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKB424_1__400x.jpg ADDED

Git LFS Details

  • SHA256: 734742497019654f13cfaa39bc875bb0c9a31c4789dbf0b381c2b9d3667c68c9
  • Pointer size: 130 Bytes
  • Size of remote file: 12 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKD0CB_1__1000x.jpg ADDED

Git LFS Details

  • SHA256: c7a6ffc12bca9243cef4f0db1eeff082c9c32e3c7e5bfb36307e7dac6bdbe60b
  • Pointer size: 130 Bytes
  • Size of remote file: 43.9 kB
tasks/brooklinen/environment/reference/clone/static/assets/img/BKD0CB_1__150x.jpg ADDED

Git LFS Details

  • SHA256: b4f6f4d7b283856fb61809d86e978e357788819e7523d4b2802a9bee17af2136
  • Pointer size: 129 Bytes
  • Size of remote file: 2.11 kB