diff options
| author | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:09:29 -0500 |
|---|---|---|
| committer | ItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com> | 2026-11-22 23:09:29 -0500 |
| commit | 5aba3f0fc3cd3acd3c9708d5eb314ec33c4ff2fe (patch) | |
| tree | 28b347bbb796091468461a1f9de3aa31f1450185 | |
| parent | 04975128eb0973601013f0cd3fad21da85585f28 (diff) | |
| parent | 3a745c68ce20132d59c83239a469a9796317babb (diff) | |
Merge pull request #3909 from airp1ane
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| -rw-r--r-- | tests/test_gallery.py | 230 | ||||
| -rw-r--r-- | tools/gallery.py | 176 |
2 files changed, 365 insertions, 41 deletions
diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 87e51c261..bb234d5de 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py | |||
| @@ -1,11 +1,15 @@ | |||
| 1 | """Unit tests for tools/gallery.py standalone 3D Studio & Asset Gallery server.""" | 1 | """Unit tests for tools/gallery.py standalone 3D Studio & Asset Gallery server.""" |
| 2 | import json | 2 | import json |
| 3 | import os | 3 | import os |
| 4 | import socket | ||
| 5 | import struct | ||
| 4 | import sys | 6 | import sys |
| 5 | import tempfile | 7 | import tempfile |
| 6 | import threading | 8 | import threading |
| 7 | import time | 9 | import time |
| 8 | import unittest | 10 | import unittest |
| 11 | from unittest import mock | ||
| 12 | import urllib.parse | ||
| 9 | import urllib.request | 13 | import urllib.request |
| 10 | 14 | ||
| 11 | HERE = os.path.dirname(os.path.abspath(__file__)) | 15 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| @@ -17,6 +21,35 @@ if TOOLS_DIR not in sys.path: | |||
| 17 | import gallery | 21 | import gallery |
| 18 | 22 | ||
| 19 | 23 | ||
| 24 | def _make_1x1_rgba_dds() -> bytes: | ||
| 25 | """Build a minimal 1x1 uncompressed RGBA DDS image for synthetic .dds -> .png preview tests.""" | ||
| 26 | hdr = bytearray(128) | ||
| 27 | hdr[0:4] = b"DDS " | ||
| 28 | struct.pack_into("<I", hdr, 4, 124) | ||
| 29 | struct.pack_into("<III", hdr, 8, 0x1007, 1, 1) | ||
| 30 | struct.pack_into("<I", hdr, 76, 32) | ||
| 31 | struct.pack_into("<I", hdr, 80, 0x41) # DDPF_RGB | DDPF_ALPHAPIXELS | ||
| 32 | struct.pack_into("<IIIII", hdr, 88, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000) | ||
| 33 | return bytes(hdr) + b"\x11\x22\x33\xff" | ||
| 34 | |||
| 35 | |||
| 36 | def _raw_get(port: int, target: str, host: str | None = "127.0.0.1", extra_headers: tuple[str, ...] = ()): | ||
| 37 | """Send a raw HTTP/1.1 GET without client-side path normalization or header merging.""" | ||
| 38 | lines = [f"GET {target} HTTP/1.1"] | ||
| 39 | if host is not None: | ||
| 40 | lines.append(f"Host: {host}") | ||
| 41 | lines.extend(extra_headers) | ||
| 42 | lines.extend(["Connection: close", "", ""]) | ||
| 43 | with socket.create_connection(("127.0.0.1", port), timeout=5) as sock: | ||
| 44 | sock.sendall("\r\n".join(lines).encode("latin-1")) | ||
| 45 | chunks = [] | ||
| 46 | while data := sock.recv(65536): | ||
| 47 | chunks.append(data) | ||
| 48 | head, _, body = b"".join(chunks).partition(b"\r\n\r\n") | ||
| 49 | status = int(head.split(b"\r\n", 1)[0].split()[1]) | ||
| 50 | return status, head.decode("latin-1"), body | ||
| 51 | |||
| 52 | |||
| 20 | class TestGalleryCategorization(unittest.TestCase): | 53 | class TestGalleryCategorization(unittest.TestCase): |
| 21 | def test_categories(self) -> None: | 54 | def test_categories(self) -> None: |
| 22 | self.assertEqual(gallery.categorize_model("ped_lucia_body.glb"), "Персонажи (Characters)") | 55 | self.assertEqual(gallery.categorize_model("ped_lucia_body.glb"), "Персонажи (Characters)") |
| @@ -32,15 +65,97 @@ class TestGalleryCategorization(unittest.TestCase): | |||
| 32 | self.assertEqual(gallery.categorize_model("model.glb", "unpacked_peds"), "Персонажи (Characters)") | 65 | self.assertEqual(gallery.categorize_model("model.glb", "unpacked_peds"), "Персонажи (Characters)") |
| 33 | 66 | ||
| 34 | 67 | ||
| 68 | class TestHostAllowed(unittest.TestCase): | ||
| 69 | def test_loopback_and_missing_hosts_are_allowed(self) -> None: | ||
| 70 | for host in (None, "127.0.0.1", "127.0.0.1:8080", "localhost", "LOCALHOST:8080", | ||
| 71 | "localhost.", "localhost.:8080", "[::1]", "[::1]:8080", " localhost "): | ||
| 72 | with self.subTest(host=host): | ||
| 73 | self.assertTrue(gallery.host_allowed(host)) | ||
| 74 | |||
| 75 | def test_foreign_and_malformed_hosts_are_refused(self) -> None: | ||
| 76 | for host in ("", "evil.example", "evil.example:8080", "127.0.0.1.evil.example", | ||
| 77 | "localhost.evil.example:8080", "0.0.0.0:8080", "::1", | ||
| 78 | "localhost:", "localhost:abc", "localhost:65536", "localhost:" + "9" * 5000, | ||
| 79 | "[::1]junk", "[::1].", "[::1]:abc", "[::1]:8080:1", "127.0.0.1:80:80"): | ||
| 80 | with self.subTest(host=host[:40]): | ||
| 81 | self.assertFalse(gallery.host_allowed(host)) | ||
| 82 | |||
| 83 | |||
| 84 | class TestSafeSubpath(unittest.TestCase): | ||
| 85 | def setUp(self) -> None: | ||
| 86 | self.tmp = tempfile.TemporaryDirectory() | ||
| 87 | self.base = os.path.join(self.tmp.name, "assets") | ||
| 88 | self.sibling = os.path.join(self.tmp.name, "assets_secret") | ||
| 89 | os.makedirs(os.path.join(self.base, "sub"), exist_ok=True) | ||
| 90 | os.makedirs(self.sibling, exist_ok=True) | ||
| 91 | with open(os.path.join(self.base, "ok.glb"), "wb") as f: | ||
| 92 | f.write(b"ok") | ||
| 93 | with open(os.path.join(self.base, "sub", "nested.glb"), "wb") as f: | ||
| 94 | f.write(b"nested") | ||
| 95 | with open(os.path.join(self.sibling, "loot.glb"), "wb") as f: | ||
| 96 | f.write(b"loot") | ||
| 97 | |||
| 98 | def tearDown(self) -> None: | ||
| 99 | self.tmp.cleanup() | ||
| 100 | |||
| 101 | def test_valid_paths_resolve_inside_base(self) -> None: | ||
| 102 | for rel in ("ok.glb", "sub/nested.glb", "COM10.glb", "my.CON"): | ||
| 103 | with self.subTest(rel=rel): | ||
| 104 | resolved = gallery.safe_subpath(self.base, rel) | ||
| 105 | self.assertIsNotNone(resolved) | ||
| 106 | self.assertEqual( | ||
| 107 | os.path.normcase(os.path.commonpath([os.path.realpath(self.base), resolved])), | ||
| 108 | os.path.normcase(os.path.realpath(self.base)), | ||
| 109 | ) | ||
| 110 | |||
| 111 | def test_traversal_and_invalid_segments_are_refused(self) -> None: | ||
| 112 | for rel in ("", "/", "\\", ".", "..", "sub", "sub/", "/ok.glb", "ok.glb/", | ||
| 113 | "../assets_secret/loot.glb", "..\\assets_secret\\loot.glb", | ||
| 114 | "sub/../../assets_secret/loot.glb", "sub//nested.glb", "./ok.glb", | ||
| 115 | "ok\x00.glb", "C:ok.glb", "ok.glb:stream"): | ||
| 116 | with self.subTest(rel=rel): | ||
| 117 | self.assertIsNone(gallery.safe_subpath(self.base, rel)) | ||
| 118 | |||
| 119 | def test_windows_device_names_refused_before_realpath(self) -> None: | ||
| 120 | names = ("CON", "con.glb", "NUL", "NUL .glb", "COM1", "COM\u00b9.glb", "LPT\u00b2.png", "CONIN$", "conout$.bin") | ||
| 121 | with mock.patch.object(gallery.os.path, "isreserved", None, create=True): | ||
| 122 | with mock.patch.object(gallery.os.path, "realpath", | ||
| 123 | side_effect=AssertionError("device path reached realpath")) as rp: | ||
| 124 | for name in names: | ||
| 125 | with self.subTest(name=name): | ||
| 126 | self.assertIsNone(gallery.safe_subpath(self.base, name)) | ||
| 127 | self.assertIsNone(gallery.safe_subpath(self.base, f"sub/{name}")) | ||
| 128 | rp.assert_not_called() | ||
| 129 | |||
| 130 | def test_symlink_escape_is_refused(self) -> None: | ||
| 131 | link = os.path.join(self.base, "escape.glb") | ||
| 132 | try: | ||
| 133 | os.symlink(os.path.join(self.sibling, "loot.glb"), link) | ||
| 134 | except (OSError, NotImplementedError) as exc: | ||
| 135 | self.skipTest(f"cannot create symlink here: {exc}") | ||
| 136 | self.assertIsNone(gallery.safe_subpath(self.base, "escape.glb")) | ||
| 137 | |||
| 138 | def test_realpath_escape_is_refused(self) -> None: | ||
| 139 | outside = os.path.realpath(os.path.join(self.sibling, "loot.glb")) | ||
| 140 | real_base = os.path.realpath(self.base) | ||
| 141 | with mock.patch.object(gallery.os.path, "realpath", | ||
| 142 | side_effect=lambda p: real_base if p == self.base else outside): | ||
| 143 | self.assertIsNone(gallery.safe_subpath(self.base, "escape.glb")) | ||
| 144 | |||
| 145 | |||
| 35 | class TestGalleryServer(unittest.TestCase): | 146 | class TestGalleryServer(unittest.TestCase): |
| 36 | def setUp(self) -> None: | 147 | def setUp(self) -> None: |
| 37 | self.tmp = tempfile.TemporaryDirectory() | 148 | self.tmp = tempfile.TemporaryDirectory() |
| 38 | self.models_dir = os.path.join(self.tmp.name, "models") | 149 | self.models_dir = os.path.join(self.tmp.name, "models") |
| 150 | self.models_secret = os.path.join(self.tmp.name, "models_secret") | ||
| 39 | self.textures_dir = os.path.join(self.tmp.name, "textures") | 151 | self.textures_dir = os.path.join(self.tmp.name, "textures") |
| 152 | self.textures_secret = os.path.join(self.tmp.name, "textures_secret") | ||
| 40 | self.viewer_dir = os.path.join(self.tmp.name, "viewer") | 153 | self.viewer_dir = os.path.join(self.tmp.name, "viewer") |
| 41 | os.makedirs(self.models_dir, exist_ok=True) | 154 | self.viewer_secret = os.path.join(self.tmp.name, "viewer_secret") |
| 42 | os.makedirs(self.textures_dir, exist_ok=True) | 155 | self.vendor_dir = os.path.join(self.viewer_dir, "vendor") |
| 43 | os.makedirs(self.viewer_dir, exist_ok=True) | 156 | for d in (self.models_dir, self.models_secret, self.textures_dir, |
| 157 | self.textures_secret, self.viewer_dir, self.viewer_secret, self.vendor_dir): | ||
| 158 | os.makedirs(d, exist_ok=True) | ||
| 44 | 159 | ||
| 45 | # Create dummy assets | 160 | # Create dummy assets |
| 46 | with open(os.path.join(self.models_dir, "test_car.glb"), "wb") as f: | 161 | with open(os.path.join(self.models_dir, "test_car.glb"), "wb") as f: |
| @@ -49,9 +164,30 @@ class TestGalleryServer(unittest.TestCase): | |||
| 49 | with open(os.path.join(self.textures_dir, "test_tex.png"), "wb") as f: | 164 | with open(os.path.join(self.textures_dir, "test_tex.png"), "wb") as f: |
| 50 | f.write(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") | 165 | f.write(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") |
| 51 | 166 | ||
| 52 | with open(os.path.join(self.viewer_dir, "studio.html"), "w", encoding="utf-8") as f: | 167 | with open(os.path.join(self.textures_dir, "inside.dds"), "wb") as f: |
| 168 | f.write(_make_1x1_rgba_dds()) | ||
| 169 | |||
| 170 | with open(os.path.join(self.viewer_dir, "studio.html"), "w", encoding="utf-8", newline="\n") as f: | ||
| 53 | f.write("<!DOCTYPE html><html><body><h1>Studio</h1></body></html>") | 171 | f.write("<!DOCTYPE html><html><body><h1>Studio</h1></body></html>") |
| 54 | 172 | ||
| 173 | with open(os.path.join(self.viewer_dir, "app.js"), "w", encoding="utf-8", newline="\n") as f: | ||
| 174 | f.write("console.log('ok');\n") | ||
| 175 | |||
| 176 | with open(os.path.join(self.vendor_dir, "three.min.js"), "w", encoding="utf-8", newline="\n") as f: | ||
| 177 | f.write("// three\n") | ||
| 178 | |||
| 179 | # Files outside the served roots that must never be served | ||
| 180 | with open(os.path.join(self.tmp.name, "secret.txt"), "wb") as f: | ||
| 181 | f.write(b"TOP_SECRET") | ||
| 182 | with open(os.path.join(self.tmp.name, "outside.dds"), "wb") as f: | ||
| 183 | f.write(_make_1x1_rgba_dds()) | ||
| 184 | with open(os.path.join(self.models_secret, "loot.glb"), "wb") as f: | ||
| 185 | f.write(b"LOOT_GLB") | ||
| 186 | with open(os.path.join(self.textures_secret, "loot.png"), "wb") as f: | ||
| 187 | f.write(b"LOOT_PNG") | ||
| 188 | with open(os.path.join(self.viewer_secret, "loot.txt"), "wb") as f: | ||
| 189 | f.write(b"LOOT_VIEWER") | ||
| 190 | |||
| 55 | # Configure handler | 191 | # Configure handler |
| 56 | gallery.StudioHandler.models_dir = self.models_dir | 192 | gallery.StudioHandler.models_dir = self.models_dir |
| 57 | gallery.StudioHandler.textures_dir = self.textures_dir | 193 | gallery.StudioHandler.textures_dir = self.textures_dir |
| @@ -91,10 +227,10 @@ class TestGalleryServer(unittest.TestCase): | |||
| 91 | with urllib.request.urlopen(f"{base}/api/textures", timeout=3) as r: | 227 | with urllib.request.urlopen(f"{base}/api/textures", timeout=3) as r: |
| 92 | self.assertEqual(r.status, 200) | 228 | self.assertEqual(r.status, 200) |
| 93 | tdata = json.loads(r.read()) | 229 | tdata = json.loads(r.read()) |
| 94 | self.assertEqual(tdata["count"], 1) | 230 | self.assertEqual(tdata["count"], 2) |
| 95 | self.assertEqual(tdata["textures"][0]["name"], "test_tex.png") | 231 | self.assertEqual([t["name"] for t in tdata["textures"]], ["inside.dds", "test_tex.png"]) |
| 96 | 232 | ||
| 97 | # 4. Binary serving | 233 | # 4. Binary serving & DDS preview fallback inside textures_dir |
| 98 | with urllib.request.urlopen(f"{base}/models/test_car.glb", timeout=3) as r: | 234 | with urllib.request.urlopen(f"{base}/models/test_car.glb", timeout=3) as r: |
| 99 | self.assertEqual(r.status, 200) | 235 | self.assertEqual(r.status, 200) |
| 100 | self.assertTrue(r.read().startswith(b"glTF")) | 236 | self.assertTrue(r.read().startswith(b"glTF")) |
| @@ -103,6 +239,86 @@ class TestGalleryServer(unittest.TestCase): | |||
| 103 | self.assertEqual(r.status, 200) | 239 | self.assertEqual(r.status, 200) |
| 104 | self.assertTrue(r.read().startswith(b"\x89PNG")) | 240 | self.assertTrue(r.read().startswith(b"\x89PNG")) |
| 105 | 241 | ||
| 242 | with urllib.request.urlopen(f"{base}/textures/inside.png", timeout=3) as r: | ||
| 243 | self.assertEqual(r.status, 200) | ||
| 244 | self.assertTrue(r.read().startswith(b"\x89PNG")) | ||
| 245 | |||
| 246 | # 5. Viewer static & vendor assets | ||
| 247 | with urllib.request.urlopen(f"{base}/vendor/three.min.js", timeout=3) as r: | ||
| 248 | self.assertEqual(r.status, 200) | ||
| 249 | self.assertIn(b"// three", r.read()) | ||
| 250 | |||
| 251 | with urllib.request.urlopen(f"{base}/app.js", timeout=3) as r: | ||
| 252 | self.assertEqual(r.status, 200) | ||
| 253 | self.assertIn(b"console.log", r.read()) | ||
| 254 | |||
| 255 | def test_traversal_and_sibling_prefix_escapes_are_forbidden(self) -> None: | ||
| 256 | host = f"127.0.0.1:{self.port}" | ||
| 257 | cases = ( | ||
| 258 | ("/vendor/../../secret.txt", b"TOP_SECRET"), | ||
| 259 | ("/vendor/%2e%2e/%2e%2e/secret.txt", b"TOP_SECRET"), | ||
| 260 | ("/models/../models_secret/loot.glb", b"LOOT_GLB"), | ||
| 261 | ("/models/..%5cmodels_secret%5cloot.glb", b"LOOT_GLB"), | ||
| 262 | ("/textures/../textures_secret/loot.png", b"LOOT_PNG"), | ||
| 263 | ("/textures/../outside.png", b"\x89PNG"), | ||
| 264 | ("/textures/%2e%2e/outside.png", b"\x89PNG"), | ||
| 265 | ("/../viewer_secret/loot.txt", b"LOOT_VIEWER"), | ||
| 266 | ("/%2e%2e/viewer_secret/loot.txt", b"LOOT_VIEWER"), | ||
| 267 | ("/%2fviewer_secret/loot.txt", b"LOOT_VIEWER"), | ||
| 268 | ("/models//test_car.glb", b"glTF"), | ||
| 269 | ) | ||
| 270 | for target, secret in cases: | ||
| 271 | with self.subTest(target=target): | ||
| 272 | status, _, body = _raw_get(self.port, target, host=host) | ||
| 273 | self.assertEqual(status, 403) | ||
| 274 | self.assertNotIn(secret, body) | ||
| 275 | |||
| 276 | def test_dds_symlink_escape_is_forbidden(self) -> None: | ||
| 277 | link = os.path.join(self.textures_dir, "escaped.dds") | ||
| 278 | try: | ||
| 279 | os.symlink(os.path.join(self.tmp.name, "outside.dds"), link) | ||
| 280 | except (OSError, NotImplementedError) as exc: | ||
| 281 | self.skipTest(f"cannot create symlink here: {exc}") | ||
| 282 | status, _, body = _raw_get(self.port, "/textures/escaped.png", host=f"127.0.0.1:{self.port}") | ||
| 283 | self.assertEqual(status, 403) | ||
| 284 | self.assertNotIn(b"\x89PNG", body) | ||
| 285 | |||
| 286 | def test_host_header_guards(self) -> None: | ||
| 287 | loopback = f"127.0.0.1:{self.port}" | ||
| 288 | for target in ("/", "/api/models", "/api/textures", "/models/test_car.glb", "/textures/test_tex.png"): | ||
| 289 | with self.subTest(case="foreign", target=target): | ||
| 290 | status, _, body = _raw_get(self.port, target, host="evil.example:8080") | ||
| 291 | self.assertEqual(status, 403) | ||
| 292 | self.assertNotIn(b"test_car.glb", body) | ||
| 293 | self.assertNotIn(b"glTF", body) | ||
| 294 | with self.subTest(case="duplicate", target=target): | ||
| 295 | status, _, body = _raw_get(self.port, target, host=loopback, extra_headers=("Host: evil.example",)) | ||
| 296 | self.assertEqual(status, 400) | ||
| 297 | self.assertNotIn(b"test_car.glb", body) | ||
| 298 | self.assertNotIn(b"glTF", body) | ||
| 299 | |||
| 300 | status, _, body = _raw_get(self.port, "/models/test_car.glb", host=None) | ||
| 301 | self.assertEqual(status, 200) | ||
| 302 | self.assertTrue(body.startswith(b"glTF")) | ||
| 303 | |||
| 304 | def test_windows_device_names_get_403_without_opening(self) -> None: | ||
| 305 | host = f"127.0.0.1:{self.port}" | ||
| 306 | targets = ("/models/COM%C2%B9.glb", "/textures/NUL%20.png", "/vendor/CONIN%24", "/AUX.js") | ||
| 307 | with mock.patch.object(gallery.os.path, "isreserved", None, create=True): | ||
| 308 | with mock.patch("builtins.open", side_effect=AssertionError("device path reached open")) as opened: | ||
| 309 | for target in targets: | ||
| 310 | with self.subTest(target=target): | ||
| 311 | status, _, _ = _raw_get(self.port, target, host=host) | ||
| 312 | self.assertEqual(status, 403) | ||
| 313 | opened.assert_not_called() | ||
| 314 | |||
| 315 | def test_missing_valid_paths_return_404(self) -> None: | ||
| 316 | host = f"127.0.0.1:{self.port}" | ||
| 317 | for target in ("/vendor/missing.js", "/models/missing.glb", "/textures/missing.png", "/missing.js"): | ||
| 318 | with self.subTest(target=target): | ||
| 319 | status, _, _ = _raw_get(self.port, target, host=host) | ||
| 320 | self.assertEqual(status, 404) | ||
| 321 | |||
| 106 | 322 | ||
| 107 | if __name__ == "__main__": | 323 | if __name__ == "__main__": |
| 108 | unittest.main() | 324 | unittest.main() |
diff --git a/tools/gallery.py b/tools/gallery.py index ec886daa7..fb1c6deaf 100644 --- a/tools/gallery.py +++ b/tools/gallery.py | |||
| @@ -42,6 +42,85 @@ def categorize_model(name: str, folder: str = "") -> str: | |||
| 42 | return "Прочее (Miscellaneous)" | 42 | return "Прочее (Miscellaneous)" |
| 43 | 43 | ||
| 44 | 44 | ||
| 45 | _WINDOWS_RESERVED_DEVICES = frozenset({ | ||
| 46 | "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", | ||
| 47 | # Windows also treats superscript 1/2/3 as device numbers; keep this fallback | ||
| 48 | # complete for Python 3.12, which has no os.path.isreserved. | ||
| 49 | *(f"COM{i}" for i in "123456789\u00b9\u00b2\u00b3"), | ||
| 50 | *(f"LPT{i}" for i in "123456789\u00b9\u00b2\u00b3"), | ||
| 51 | }) | ||
| 52 | |||
| 53 | |||
| 54 | def _is_reserved_segment(seg: str) -> bool: | ||
| 55 | stem = seg.split(".", 1)[0].rstrip(" ").upper() | ||
| 56 | if stem in _WINDOWS_RESERVED_DEVICES: | ||
| 57 | return True | ||
| 58 | isreserved = getattr(os.path, "isreserved", None) | ||
| 59 | if callable(isreserved) and isreserved(seg): | ||
| 60 | return True | ||
| 61 | return False | ||
| 62 | |||
| 63 | |||
| 64 | # Binding to 127.0.0.1 keeps other machines out, but not other web pages: a page on any site can point its own | ||
| 65 | # domain at 127.0.0.1 (DNS rebinding) and read local assets through this server as same-origin. | ||
| 66 | _LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "[::1]"}) | ||
| 67 | |||
| 68 | |||
| 69 | def host_allowed(host: str | None) -> bool: | ||
| 70 | """True when a request's Host header names the loopback address. Browsers always send Host; a request without | ||
| 71 | one comes from a local tool, not a web page, and is allowed.""" | ||
| 72 | if host is None: | ||
| 73 | return True | ||
| 74 | host = host.strip(" \t").lower() | ||
| 75 | if host.startswith("["): # [::1] or [::1]:8080 | ||
| 76 | end = host.find("]") | ||
| 77 | if end < 0: | ||
| 78 | return False | ||
| 79 | name, rest = host[:end + 1], host[end + 1:] | ||
| 80 | if rest and not rest.startswith(":"): | ||
| 81 | return False # [::1]junk, [::1]. | ||
| 82 | port = rest[1:] if rest else None | ||
| 83 | else: | ||
| 84 | name, colon, port = host.partition(":") | ||
| 85 | if not colon: | ||
| 86 | port = None | ||
| 87 | elif ":" in port: | ||
| 88 | return False # a bare IPv6 address, or name:port:more | ||
| 89 | if name.endswith("."): # one trailing dot: the fully qualified form | ||
| 90 | name = name[:-1] | ||
| 91 | if port is not None and not (0 < len(port) <= 5 and port.isascii() and port.isdigit() and int(port) <= 65535): | ||
| 92 | return False | ||
| 93 | return name in _LOOPBACK_HOSTS | ||
| 94 | |||
| 95 | |||
| 96 | def safe_subpath(base_dir: str, rel: str) -> str | None: | ||
| 97 | """Resolve a relative URL path safely inside base_dir, or return None.""" | ||
| 98 | if not base_dir or not isinstance(rel, str) or not rel or "\x00" in rel: | ||
| 99 | return None | ||
| 100 | if rel.startswith(("/", "\\")) or rel.endswith(("/", "\\")): | ||
| 101 | return None | ||
| 102 | norm = rel.replace("\\", "/") | ||
| 103 | if os.path.isabs(rel) or os.path.isabs(norm): | ||
| 104 | return None | ||
| 105 | parts = norm.split("/") | ||
| 106 | for seg in parts: | ||
| 107 | if not seg or seg in (".", "..") or ":" in seg or _is_reserved_segment(seg): | ||
| 108 | return None | ||
| 109 | real_base = os.path.realpath(base_dir) | ||
| 110 | real_target = os.path.realpath(os.path.join(real_base, *parts)) | ||
| 111 | try: | ||
| 112 | common = os.path.commonpath([real_base, real_target]) | ||
| 113 | except ValueError: | ||
| 114 | return None | ||
| 115 | if os.path.normcase(common) != os.path.normcase(real_base): | ||
| 116 | return None | ||
| 117 | if os.path.normcase(real_target) == os.path.normcase(real_base): | ||
| 118 | return None | ||
| 119 | if os.path.isdir(real_target): | ||
| 120 | return None | ||
| 121 | return real_target | ||
| 122 | |||
| 123 | |||
| 45 | class StudioHandler(http.server.BaseHTTPRequestHandler): | 124 | class StudioHandler(http.server.BaseHTTPRequestHandler): |
| 46 | models_dir: str = "" | 125 | models_dir: str = "" |
| 47 | textures_dir: str = "" | 126 | textures_dir: str = "" |
| @@ -50,11 +129,23 @@ class StudioHandler(http.server.BaseHTTPRequestHandler): | |||
| 50 | def log_message(self, format: str, *args: object) -> None: | 129 | def log_message(self, format: str, *args: object) -> None: |
| 51 | pass # Quiet logging | 130 | pass # Quiet logging |
| 52 | 131 | ||
| 132 | def _check_host(self) -> bool: | ||
| 133 | hosts = self.headers.get_all("Host", []) | ||
| 134 | if len(hosts) > 1: | ||
| 135 | self.send_error(400, "Duplicate Host header") | ||
| 136 | return False | ||
| 137 | if not host_allowed(hosts[0] if hosts else None): | ||
| 138 | self.send_error(403, "Forbidden: open the gallery at http://127.0.0.1 or http://localhost") | ||
| 139 | return False | ||
| 140 | return True | ||
| 141 | |||
| 53 | def do_GET(self) -> None: | 142 | def do_GET(self) -> None: |
| 54 | parsed = urllib.parse.urlparse(self.path) | 143 | if not self._check_host(): |
| 55 | path = urllib.parse.unquote(parsed.path) | 144 | return |
| 56 | 145 | ||
| 57 | if path in ("/", "/index.html", "/studio.html"): | 146 | clean = self.path.split("#", 1)[0].split("?", 1)[0] |
| 147 | |||
| 148 | if clean in ("/", "/index.html", "/studio.html"): | ||
| 58 | studio_path = os.path.join(self.viewer_dir, "studio.html") | 149 | studio_path = os.path.join(self.viewer_dir, "studio.html") |
| 59 | index_path = os.path.join(self.viewer_dir, "index.html") | 150 | index_path = os.path.join(self.viewer_dir, "index.html") |
| 60 | target = studio_path if os.path.isfile(studio_path) else index_path | 151 | target = studio_path if os.path.isfile(studio_path) else index_path |
| @@ -64,9 +155,20 @@ class StudioHandler(http.server.BaseHTTPRequestHandler): | |||
| 64 | self.send_error(404, "Viewer page not found") | 155 | self.send_error(404, "Viewer page not found") |
| 65 | return | 156 | return |
| 66 | 157 | ||
| 67 | if path.startswith("/vendor/"): | 158 | if clean == "/api/models": |
| 68 | rel = path[len("/vendor/"):].lstrip("/") | 159 | self._serve_models_json() |
| 69 | vpath = os.path.normpath(os.path.join(self.viewer_dir, "vendor", rel)) | 160 | return |
| 161 | |||
| 162 | if clean == "/api/textures": | ||
| 163 | self._serve_textures_json() | ||
| 164 | return | ||
| 165 | |||
| 166 | if clean.startswith("/vendor/"): | ||
| 167 | rel = urllib.parse.unquote(clean[len("/vendor/"):]) | ||
| 168 | vpath = safe_subpath(os.path.join(self.viewer_dir, "vendor"), rel) | ||
| 169 | if vpath is None: | ||
| 170 | self.send_error(403, "Forbidden") | ||
| 171 | return | ||
| 70 | if os.path.isfile(vpath): | 172 | if os.path.isfile(vpath): |
| 71 | mime = mimetypes.guess_type(vpath)[0] or "application/javascript" | 173 | mime = mimetypes.guess_type(vpath)[0] or "application/javascript" |
| 72 | self._send_file(vpath, mime) | 174 | self._send_file(vpath, mime) |
| @@ -74,42 +176,32 @@ class StudioHandler(http.server.BaseHTTPRequestHandler): | |||
| 74 | self.send_error(404, "Vendor file not found") | 176 | self.send_error(404, "Vendor file not found") |
| 75 | return | 177 | return |
| 76 | 178 | ||
| 77 | # Serve static assets from viewer directory (e.g. style.css, app.js) | 179 | if clean.startswith("/models/"): |
| 78 | rel_viewer = path.lstrip("/") | 180 | rel = urllib.parse.unquote(clean[len("/models/"):]) |
| 79 | vfile = os.path.normpath(os.path.join(self.viewer_dir, rel_viewer)) | 181 | mpath = safe_subpath(self.models_dir, rel) |
| 80 | if os.path.isfile(vfile) and vfile.startswith(self.viewer_dir): | 182 | if mpath is None: |
| 81 | mime = mimetypes.guess_type(vfile)[0] or "application/octet-stream" | 183 | self.send_error(403, "Forbidden") |
| 82 | if mime.startswith("text/"): | 184 | return |
| 83 | mime += "; charset=utf-8" | 185 | if os.path.isfile(mpath): |
| 84 | self._send_file(vfile, mime) | ||
| 85 | return | ||
| 86 | |||
| 87 | if path == "/api/models": | ||
| 88 | self._serve_models_json() | ||
| 89 | return | ||
| 90 | |||
| 91 | if path == "/api/textures": | ||
| 92 | self._serve_textures_json() | ||
| 93 | return | ||
| 94 | |||
| 95 | if path.startswith("/models/"): | ||
| 96 | rel = path[len("/models/"):].lstrip("/") | ||
| 97 | mpath = os.path.normpath(os.path.join(self.models_dir, rel)) | ||
| 98 | # Security: ensure mpath is inside models_dir | ||
| 99 | if os.path.isfile(mpath) and mpath.startswith(self.models_dir): | ||
| 100 | self._send_file(mpath, "model/gltf-binary") | 186 | self._send_file(mpath, "model/gltf-binary") |
| 101 | else: | 187 | else: |
| 102 | self.send_error(404, "Model not found") | 188 | self.send_error(404, "Model not found") |
| 103 | return | 189 | return |
| 104 | 190 | ||
| 105 | if path.startswith("/textures/"): | 191 | if clean.startswith("/textures/"): |
| 106 | rel = path[len("/textures/"):].lstrip("/") | 192 | rel = urllib.parse.unquote(clean[len("/textures/"):]) |
| 107 | tpath = os.path.normpath(os.path.join(self.textures_dir, rel)) | 193 | tpath = safe_subpath(self.textures_dir, rel) |
| 194 | if tpath is None: | ||
| 195 | self.send_error(403, "Forbidden") | ||
| 196 | return | ||
| 108 | 197 | ||
| 109 | if not os.path.isfile(tpath) and rel.lower().endswith(".png"): | 198 | if not os.path.isfile(tpath) and rel.lower().endswith(".png"): |
| 110 | # Try matching .dds file if png requested | 199 | # Try matching .dds file if png requested |
| 111 | stem = os.path.splitext(rel)[0] | 200 | stem = os.path.splitext(rel)[0] |
| 112 | dds_cand = os.path.normpath(os.path.join(self.textures_dir, stem + ".dds")) | 201 | dds_cand = safe_subpath(self.textures_dir, stem + ".dds") |
| 202 | if dds_cand is None: | ||
| 203 | self.send_error(403, "Forbidden") | ||
| 204 | return | ||
| 113 | if os.path.isfile(dds_cand) and dds_png: | 205 | if os.path.isfile(dds_cand) and dds_png: |
| 114 | try: | 206 | try: |
| 115 | png_bytes = dds_png.dds_file_to_png_bytes(dds_cand, max_size=1024) | 207 | png_bytes = dds_png.dds_file_to_png_bytes(dds_cand, max_size=1024) |
| @@ -123,13 +215,29 @@ class StudioHandler(http.server.BaseHTTPRequestHandler): | |||
| 123 | except Exception: | 215 | except Exception: |
| 124 | pass | 216 | pass |
| 125 | 217 | ||
| 126 | if os.path.isfile(tpath) and tpath.startswith(self.textures_dir): | 218 | if os.path.isfile(tpath): |
| 127 | mime = mimetypes.guess_type(tpath)[0] or "application/octet-stream" | 219 | mime = mimetypes.guess_type(tpath)[0] or "application/octet-stream" |
| 128 | self._send_file(tpath, mime) | 220 | self._send_file(tpath, mime) |
| 129 | else: | 221 | else: |
| 130 | self.send_error(404, "Texture not found") | 222 | self.send_error(404, "Texture not found") |
| 131 | return | 223 | return |
| 132 | 224 | ||
| 225 | # Serve static assets from viewer directory (e.g. style.css, app.js) | ||
| 226 | if not clean.startswith("/"): | ||
| 227 | self.send_error(403, "Forbidden") | ||
| 228 | return | ||
| 229 | rel_viewer = urllib.parse.unquote(clean[1:]) | ||
| 230 | vfile = safe_subpath(self.viewer_dir, rel_viewer) | ||
| 231 | if vfile is None: | ||
| 232 | self.send_error(403, "Forbidden") | ||
| 233 | return | ||
| 234 | if os.path.isfile(vfile): | ||
| 235 | mime = mimetypes.guess_type(vfile)[0] or "application/octet-stream" | ||
| 236 | if mime.startswith("text/"): | ||
| 237 | mime += "; charset=utf-8" | ||
| 238 | self._send_file(vfile, mime) | ||
| 239 | return | ||
| 240 | |||
| 133 | self.send_error(404, "Not Found") | 241 | self.send_error(404, "Not Found") |
| 134 | 242 | ||
| 135 | def _send_file(self, file_path: str, content_type: str) -> None: | 243 | def _send_file(self, file_path: str, content_type: str) -> None: |