Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(workers): harden cad-forge sandbox policy, texture projection and the crawler guard, and the multiplayer game token, with matching tests

nirholasc832c83c3a1a
diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.js
index ee6a08b7e..eb6ce7c37 100644
--- a/multiplayer/src/game-token.js
+++ b/multiplayer/src/game-token.js
@@ -275,11 +275,28 @@ export async function verifySplitPayment({ txSig, sellerWallet, sellerRaw, treas
const sellerGain = delta(sellerATA);
const treasuryGain = delta(treasuryATA);
- if (sellerGain < BigInt(sellerRaw)) return { ok: false, reason: 'seller_underpaid' };
- if (treasuryGain < BigInt(treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
+ const underpaid = underpaidLeg(delta, [
+ { ata: sellerATA, raw: BigInt(sellerRaw), reason: 'seller_underpaid' },
+ { ata: treasuryATA, raw: BigInt(treasuryRaw), reason: 'treasury_underpaid' },
+ ]);
+ if (underpaid) return { ok: false, reason: underpaid };
return { ok: true, sellerGain: sellerGain.toString(), treasuryGain: treasuryGain.toString() };
}
+// Check each payment leg against the token-account delta. When several legs
+// pay the same token account (REWARDS_SINK falls back to the treasury), that
+// account must have gained the SUM of those legs; checking each leg against the
+// shared delta independently would let one half-price transfer satisfy both.
+// `legs` is ordered; the first underfunded leg's reason is returned.
+function underpaidLeg(delta, legs) {
+ const owed = new Map();
+ for (const l of legs) owed.set(l.ata, (owed.get(l.ata) || 0n) + l.raw);
+ for (const l of legs) {
+ if (delta(l.ata) < owed.get(l.ata)) return l.reason;
+ }
+ return null;
+}
+
// Resolve the account address for a token-balance entry's index across the
// transaction's account-key list (parsed transactions expose keys as objects).
function accountKeyAt(tx, index) {
@@ -439,16 +456,16 @@ export async function verifySpinPayment({ quoteToken, txSig, buyerWallet, forAcc
const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');
};
- if (delta(rewardsATA) < BigInt(q.rewardsRaw)) return { ok: false, reason: 'rewards_underpaid' };
- if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
- // Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
- // must have moved at least that share to the creator's $THREE account — else the
- // split didn't happen and we refuse to credit the sale. Quotes without a creator
- // leg (spins, plain boutique sales) skip this and behave exactly as before.
+ const legs = [
+ { ata: rewardsATA, raw: BigInt(q.rewardsRaw), reason: 'rewards_underpaid' },
+ { ata: treasuryATA, raw: BigInt(q.treasuryRaw), reason: 'treasury_underpaid' },
+ ];
if (q.creatorAddr && BigInt(q.creatorRaw || '0') > 0n) {
const creatorATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.creatorAddr))).toBase58();
- if (delta(creatorATA) < BigInt(q.creatorRaw)) return { ok: false, reason: 'creator_underpaid' };
+ legs.push({ ata: creatorATA, raw: BigInt(q.creatorRaw), reason: 'creator_underpaid' });
}
+ const underpaid = underpaidLeg(delta, legs);
+ if (underpaid) return { ok: false, reason: underpaid };
return { ok: true, nonce: q.nonce, quote: q };
}
@@ -606,15 +623,15 @@ export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purp
const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);
return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');
};
- if (delta(rewardsATA) < BigInt(q.rewardsRaw)) return { ok: false, reason: 'rewards_underpaid' };
- if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };
- // Creator leg (R25): when the quote sealed a creator transfer, the on-chain tx
- // must have moved at least that share to the creator's $THREE account — else the
- // split didn't happen and we refuse to credit the sale. Quotes without a creator
- // leg (spins, plain boutique sales) skip this and behave exactly as before.
+ const legs = [
+ { ata: rewardsATA, raw: BigInt(q.rewardsRaw), reason: 'rewards_underpaid' },
+ { ata: treasuryATA, raw: BigInt(q.treasuryRaw), reason: 'treasury_underpaid' },
+ ];
if (q.creatorAddr && BigInt(q.creatorRaw || '0') > 0n) {
const creatorATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.creatorAddr))).toBase58();
- if (delta(creatorATA) < BigInt(q.creatorRaw)) return { ok: false, reason: 'creator_underpaid' };
+ legs.push({ ata: creatorATA, raw: BigInt(q.creatorRaw), reason: 'creator_underpaid' });
}
+ const underpaid = underpaidLeg(delta, legs);
+ if (underpaid) return { ok: false, reason: underpaid };
return { ok: true, nonce: q.nonce, quote: q };
}
diff --git a/workers/agent-crawler/guard.js b/workers/agent-crawler/guard.js
index 15031adb8..c423e555f 100644
--- a/workers/agent-crawler/guard.js
+++ b/workers/agent-crawler/guard.js
@@ -7,7 +7,10 @@
// Dependency-free so tests/agent-crawler-guard.test.js can pin it.
import dns from 'node:dns/promises';
+import http from 'node:http';
+import https from 'node:https';
import net from 'node:net';
+import { Readable } from 'node:stream';
export const BOT_TOKEN = 'three.ws-crawler';
export const USER_AGENT =
@@ -54,6 +57,48 @@ export async function guardHost(hostname) {
return ok;
}
+// The address a hostname connects to is decided HERE, at connect time, and the
+// socket uses exactly that address. guardHost() alone checks one lookup and then
+// lets the HTTP client resolve again, so a DNS answer that flips between the two
+// (rebinding) would slip a private address past the fence.
+export function guardedLookup(hostname, options, callback) {
+ const cb = typeof options === 'function' ? options : callback;
+ const wantAll = typeof options === 'object' && options?.all === true;
+ dns.lookup(hostname, { all: true, verbatim: true }).then(
+ (addrs) => {
+ if (!addrs.length || addrs.some((a) => isBlockedAddress(a.address))) {
+ cb(new Error(`refused private host ${hostname}`));
+ return;
+ }
+ if (wantAll) cb(null, addrs);
+ else cb(null, addrs[0].address, addrs[0].family);
+ },
+ (err) => cb(err),
+ );
+}
+
+function pinnedRequest(u, { headers, signal }) {
+ return new Promise((resolve, reject) => {
+ const client = u.protocol === 'https:' ? https : http;
+ const req = client.request(
+ u,
+ { method: 'GET', headers, lookup: guardedLookup, signal },
+ (res) => {
+ const responseHeaders = new Headers();
+ for (const [k, v] of Object.entries(res.headers)) {
+ if (Array.isArray(v)) for (const item of v) responseHeaders.append(k, item);
+ else if (v !== undefined) responseHeaders.set(k, v);
+ }
+ const noBody = [101, 204, 205, 304].includes(res.statusCode);
+ if (noBody) res.resume();
+ resolve(new Response(noBody ? null : Readable.toWeb(res), { status: res.statusCode, headers: responseHeaders }));
+ },
+ );
+ req.on('error', reject);
+ req.end();
+ });
+}
+
// fetch() for the crawler's own side requests (robots.txt, search reseeds),
// with the same host fence and a hard timeout. Redirects are followed by hand so
// every hop's host passes guardHost before we connect to it; following them
@@ -66,11 +111,10 @@ export async function guardedFetch(url, { timeoutMs = 8000, headers = {} } = {})
for (let hops = 0; ; hops++) {
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new Error(`refused scheme ${u.protocol}`);
if (!(await guardHost(u.hostname))) throw new Error(`refused private host ${u.hostname}`);
- const res = await fetch(u, {
- headers: { 'user-agent': USER_AGENT, accept: '*/*', ...headers },
- redirect: 'manual',
- signal,
- });
+ const requestHeaders = { 'user-agent': USER_AGENT, accept: '*/*', ...headers };
+ const res = net.isIP(u.hostname.replace(/^\[|\]$/g, ''))
+ ? await fetch(u, { headers: requestHeaders, redirect: 'manual', signal })
+ : await pinnedRequest(u, { headers: requestHeaders, signal });
const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
if (!location) return res;
await res.body?.cancel().catch(() => {});
diff --git a/workers/cad-forge/cad_policy.py b/workers/cad-forge/cad_policy.py
index 3ceb3b540..eb43725ea 100644
--- a/workers/cad-forge/cad_policy.py
+++ b/workers/cad-forge/cad_policy.py
@@ -54,6 +54,21 @@ BANNED_NAMES = frozenset({
"__import__", "__builtins__", "__loader__", "__spec__",
})
+# build123d functions and methods that take a filesystem path. The runner
+# writes every artifact itself, and each job's workdir is owned by an
+# unprivileged uid that a sibling job may share, so a program has no reason to
+# name a path at all. Matched by exact name here and by prefix below.
+BANNED_IO_NAMES = frozenset({
+ "Mesher", "ExportSVG", "ExportDXF", "ImportSVG", "ImportDXF",
+ "read", "write", "load", "save", "dump", "dumps",
+})
+BANNED_IO_PREFIXES = ("export", "import_")
+
+
+def _is_io_name(name: str) -> bool:
+ return name in BANNED_IO_NAMES or name.startswith(BANNED_IO_PREFIXES)
+
+
# Attribute names that perform attribute lookups from inside a string.
BANNED_ATTRIBUTES = frozenset({"format", "format_map", "vformat", "mro"})
@@ -138,11 +153,15 @@ def check_source(source: str) -> ast.Module:
raise PolicyViolation(f"'from {node.module} import *' is not allowed; import the names you use.", line)
if alias.name != "*" and alias.name.startswith("_"):
raise PolicyViolation(f"importing '{alias.name}' is not allowed.", line)
+ if alias.name != "*" and _is_io_name(alias.name):
+ raise PolicyViolation(f"importing '{alias.name}' is not allowed; files are exported by the runner.", line)
elif isinstance(node, ast.Attribute):
if node.attr.startswith("_"):
raise PolicyViolation(f"access to '.{node.attr}' is not allowed.", line)
if node.attr in INTROSPECTION_ATTRIBUTES or node.attr.startswith(INTROSPECTION_PREFIXES):
raise PolicyViolation(f"access to '.{node.attr}' is not allowed.", line)
+ if _is_io_name(node.attr):
+ raise PolicyViolation(f"access to '.{node.attr}' is not allowed; files are exported by the runner.", line)
if node.attr in BANNED_ATTRIBUTES:
raise PolicyViolation(f"'.{node.attr}' is not available; use an f-string instead.", line)
elif isinstance(node, ast.Name):
@@ -150,6 +169,8 @@ def check_source(source: str) -> ast.Module:
raise PolicyViolation(f"'{node.id}' is not available in a CAD program.", line)
if node.id.startswith("__"):
raise PolicyViolation(f"the name '{node.id}' is not allowed.", line)
+ if _is_io_name(node.id):
+ raise PolicyViolation(f"'{node.id}' is not available in a CAD program; files are exported by the runner.", line)
elif isinstance(node, (ast.Yield, ast.YieldFrom)):
raise PolicyViolation("yield is not allowed; build the part with plain functions.", line)
elif isinstance(node, (ast.AsyncFunctionDef, ast.Await, ast.AsyncFor, ast.AsyncWith)):
diff --git a/workers/cad-forge/main.py b/workers/cad-forge/main.py
index 25199b03a..783971ff8 100644
--- a/workers/cad-forge/main.py
+++ b/workers/cad-forge/main.py
@@ -38,6 +38,7 @@ import stat
import shutil
import subprocess
import sys
+import itertools
import tempfile
import threading
import time
@@ -63,6 +64,16 @@ REQUIRE_SECCOMP = os.environ.get("REQUIRE_SECCOMP", "1") != "0"
CHILD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_child.py")
SANDBOX_UID = 65534 # nobody
+# Each child runs as its own uid from this block, so one job's program cannot
+# open a sibling job's workdir even if it learns the path. The block is far
+# larger than WARM_POOL + MAX_CONCURRENT, so live children never share a uid.
+SANDBOX_UID_BASE = int(os.environ.get("SANDBOX_UID_BASE", "200000"))
+SANDBOX_UID_SPAN = 20000
+_uid_counter = itertools.count()
+
+
+def next_sandbox_uid() -> int:
+ return SANDBOX_UID_BASE + (next(_uid_counter) % SANDBOX_UID_SPAN)
MEMORY_LIMIT_BYTES = int(os.environ.get("SANDBOX_MEMORY_MB", "3072")) * 1024 * 1024
CPU_LIMIT_S = int(BUILD_TIMEOUT_S * 2)
MAX_ARTIFACT_BYTES = 24 * 1024 * 1024
@@ -95,8 +106,9 @@ class Child:
def _spawn() -> Child:
workdir = tempfile.mkdtemp(prefix="cad-")
drop = os.geteuid() == 0
+ uid = next_sandbox_uid()
if drop:
- os.chown(workdir, SANDBOX_UID, SANDBOX_UID)
+ os.chown(workdir, uid, uid)
env = {
"PATH": "/usr/local/bin:/usr/bin:/bin",
"HOME": workdir,
@@ -116,8 +128,8 @@ def _spawn() -> Child:
stderr=subprocess.PIPE,
close_fds=True,
preexec_fn=_limits,
- user=SANDBOX_UID if drop else None,
- group=SANDBOX_UID if drop else None,
+ user=uid if drop else None,
+ group=uid if drop else None,
extra_groups=[] if drop else None,
)
return Child(proc=proc, workdir=workdir, started=time.monotonic())
diff --git a/workers/cad-forge/test_cad_policy.py b/workers/cad-forge/test_cad_policy.py
index a6dfac7f2..bc2894510 100644
--- a/workers/cad-forge/test_cad_policy.py
+++ b/workers/cad-forge/test_cad_policy.py
@@ -116,6 +116,22 @@ class PolicyTests(unittest.TestCase):
def test_accepts_comprehensions_and_generator_expressions(self):
check_source("total = sum(i * 2 for i in range(4))\nxs = [i for i in range(3)]\n")
+ def test_refuses_path_taking_io_names(self):
+ # These write or read an arbitrary path with the sandbox uid, which
+ # every sibling job's workdir shares. The runner exports by itself.
+ for name in ("export_step", "export_stl", "export_gltf", "export_svg",
+ "import_step", "import_stl", "import_svg", "Mesher",
+ "ExportSVG", "ExportDXF", "ImportSVG", "ImportDXF"):
+ self.assertRefused(f"from build123d import {name}\n", "is not allowed")
+ self.assertRefused(f"x = {name}\n", "is not available")
+ self.assertRefused("part.export_step('/tmp/cad-x/part.step')\n", "is not allowed")
+ self.assertRefused("part.import_stl('/tmp/a')\n", "is not allowed")
+ self.assertRefused("part.write('/tmp/a')\n", "is not allowed")
+ self.assertRefused("part.read('/tmp/a')\n", "is not allowed")
+
+ def test_still_accepts_plain_modeling(self):
+ check_source("from build123d import *\nwith BuildPart() as p:\n Box(1, 2, 3)\nresult = p.part\n")
+
if __name__ == "__main__":
unittest.main(verbosity=1)
diff --git a/workers/cad-forge/test_sandbox.py b/workers/cad-forge/test_sandbox.py
index c36775e3b..628532b7e 100644
--- a/workers/cad-forge/test_sandbox.py
+++ b/workers/cad-forge/test_sandbox.py
@@ -252,6 +252,13 @@ class IsolationLayerTests(unittest.TestCase):
self.assertNotEqual(results["parent_env"], "read")
+class PerJobUidTests(unittest.TestCase):
+ def test_live_children_never_share_a_uid(self):
+ uids = [main.next_sandbox_uid() for _ in range(main.SANDBOX_UID_SPAN)]
+ self.assertEqual(len(set(uids)), main.SANDBOX_UID_SPAN)
+ self.assertTrue(all(u >= main.SANDBOX_UID_BASE for u in uids))
+
+
class CollectTests(unittest.TestCase):
def test_collect_does_not_follow_symlinked_artifacts(self):
import tempfile
diff --git a/workers/remesh/test_gltf_meshopt.py b/workers/remesh/test_gltf_meshopt.py
index 2d2e9d502..873c6cc77 100644
--- a/workers/remesh/test_gltf_meshopt.py
+++ b/workers/remesh/test_gltf_meshopt.py
@@ -138,4 +138,50 @@ else:
finally:
gltf_meshopt.GLTFPACK_BIN = original_bin
+# ── external references are refused before gltfpack ever runs ─────────────────────
+#
+# gltfpack (cgltf) resolves buffers[].uri / images[].uri relative to the input
+# file's directory, so a caller-supplied document naming "../../etc/passwd" would
+# read a file off the worker and return it inside the decoded GLB. The check
+# must fire before the binary is invoked, so these run with or without gltfpack.
+
+import json as _json
+
+_original_bin = gltf_meshopt.GLTFPACK_BIN
+gltf_meshopt.GLTFPACK_BIN = "gltfpack-not-installed"
+
+
+def _hostile(uri_field: str, uri: str, suffix: str) -> bytes:
+ doc = {
+ "asset": {"version": "2.0"},
+ "extensionsUsed": [gltf_meshopt.MESHOPT_EXTENSION],
+ "buffers": [{"byteLength": 16}],
+ "images": [],
+ }
+ doc[uri_field] = [{"uri": uri, "byteLength": 16}]
+ raw = _json.dumps(doc).encode()
+ if suffix == ".gltf":
+ return raw
+ raw += b" " * (-len(raw) % 4)
+ return b"glTF" + (2).to_bytes(4, "little") + (28 + len(raw)).to_bytes(4, "little") + len(raw).to_bytes(4, "little") + b"JSON" + raw
+
+
+for field, uri in (("buffers", "../../etc/passwd"), ("buffers", "/etc/passwd"), ("buffers", "file:///etc/passwd"), ("images", "../secret.png"), ("buffers", "http://169.254.169.254/x")):
+ for suffix in (".gltf", ".glb"):
+ label = f"{suffix} with {field}[].uri {uri!r}"
+ try:
+ gltf_meshopt.transcode_meshopt(_hostile(field, uri, suffix), suffix)
+ check(f"{label} is refused", False, "no ValueError raised")
+ except ValueError as exc:
+ check(f"{label} is refused", "external" in str(exc), str(exc))
+
+_data_ok = {
+ "asset": {"version": "2.0"},
+ "extensionsUsed": [gltf_meshopt.MESHOPT_EXTENSION],
+ "buffers": [{"uri": "data:application/octet-stream;base64,AAAA", "byteLength": 3}],
+}
+check("data: URIs are not external references", gltf_meshopt.external_references(_data_ok) == [])
+check("a uri-less GLB buffer is not an external reference", gltf_meshopt.external_references({"buffers": [{"byteLength": 4}]}) == [])
+gltf_meshopt.GLTFPACK_BIN = _original_bin
+
print(f"\n{PASS} checks passed")
diff --git a/workers/texture/main.py b/workers/texture/main.py
index 797095370..b112c7c04 100644
--- a/workers/texture/main.py
+++ b/workers/texture/main.py
@@ -131,6 +131,10 @@ SDXL_INPAINT_MODEL = os.environ.get(
"SDXL_INPAINT_MODEL", "diffusers/stable-diffusion-xl-1.0-inpainting-0.1"
)
MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))
+# A job that outlives this is reported failed to the caller. Threads cannot be
+# killed, so the concurrency slot stays held until the worker thread returns:
+# a stuck job can never admit more work than MAX_CONCURRENT.
+JOB_TIMEOUT_S = int(os.environ.get("JOB_TIMEOUT_S", "540"))
# Every checkpoint here is loaded in half precision and run on an L4, so the
# fp16 variant of each repo is the only one this service ever uses. Naming it
@@ -379,6 +383,7 @@ def _load_mesh(url: str):
if isinstance(mesh, trimesh.Scene):
meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]
mesh = trimesh.util.concatenate(meshes)
+ tp.assert_face_budget(len(mesh.faces))
if not hasattr(mesh.visual, "uv") or mesh.visual.uv is None:
# Auto-unwrap using trimesh's built-in UV generation
mesh = mesh.unwrap()
@@ -573,7 +578,7 @@ def _build_masks(
boundary fades out smoothly (invisible seam). Texels at alpha 0 are left
bit-identical.
"""
- src = Image.open(io.BytesIO(mask_bytes)).convert("L").resize(size, Image.LANCZOS)
+ src = tp.open_bounded_image(mask_bytes).convert("L").resize(size, Image.LANCZOS)
arr = np.asarray(src, dtype=np.uint8)
hard = (arr > 127).astype(np.uint8) * 255
if not hard.any():
@@ -625,8 +630,10 @@ def _load_textured_mesh(url: str):
if getattr(g.visual, "uv", None) is not None
]
name, mesh = max(textured or geoms, key=lambda ng: len(ng[1].faces))
+ tp.assert_face_budget(sum(len(g.faces) for _, g in geoms))
return loaded, name, mesh
+ tp.assert_face_budget(len(loaded.faces))
scene = trimesh.Scene(geometry={"mesh": loaded})
return scene, "mesh", loaded
@@ -769,7 +776,18 @@ async def _run_task(task_id: str, runner: Callable[[], bytes], label: str) -> No
loop = asyncio.get_event_loop()
t0 = time.time()
try:
- glb_bytes = await loop.run_in_executor(None, runner)
+ job = asyncio.ensure_future(loop.run_in_executor(None, runner))
+ try:
+ glb_bytes = await asyncio.wait_for(asyncio.shield(job), JOB_TIMEOUT_S)
+ except asyncio.TimeoutError:
+ _tasks[task_id].update({
+ "status": "failed",
+ "error": f"job exceeded the {JOB_TIMEOUT_S}s time limit",
+ "elapsed_ms": int((time.time() - t0) * 1000),
+ })
+ log.error("[%s] %s timed out after %ds", task_id, label, JOB_TIMEOUT_S)
+ await asyncio.gather(job, return_exceptions=True)
+ return
blob_name = f"textured/{task_id}.glb"
blob = _bucket.blob(blob_name)
diff --git a/workers/texture/test_texture_projection.py b/workers/texture/test_texture_projection.py
index 6b2368cab..d70854ce8 100644
--- a/workers/texture/test_texture_projection.py
+++ b/workers/texture/test_texture_projection.py
@@ -287,7 +287,42 @@ def test_gap_fill_never_leaves_a_hole():
print("ok gap fill pads every unwritten texel")
+def test_face_budget_refuses_an_oversized_mesh():
+ tp.assert_face_budget(tp.MAX_MESH_FACES)
+ try:
+ tp.assert_face_budget(tp.MAX_MESH_FACES + 1)
+ except ValueError as exc:
+ assert "faces" in str(exc)
+ else:
+ raise AssertionError("an over-budget mesh must be refused")
+ print("ok face budget refuses an oversized mesh")
+
+
+def test_image_decode_refuses_a_decompression_bomb():
+ import io
+
+ from PIL import Image
+
+ ok = io.BytesIO()
+ Image.new("L", (8, 8)).save(ok, format="PNG")
+ assert tp.open_bounded_image(ok.getvalue()).size == (8, 8)
+
+ # 20000 x 20000 solid grey compresses to well under a megabyte but would
+ # decode to 400 MP. The header alone must be enough to refuse it.
+ bomb = io.BytesIO()
+ Image.new("L", (20000, 20000)).save(bomb, format="PNG", compress_level=9)
+ try:
+ tp.open_bounded_image(bomb.getvalue())
+ except ValueError as exc:
+ assert "pixels" in str(exc)
+ else:
+ raise AssertionError("a decompression bomb must be refused before decode")
+ print("ok image decode refuses a decompression bomb")
+
+
TESTS = [
+ test_face_budget_refuses_an_oversized_mesh,
+ test_image_decode_refuses_a_decompression_bomb,
test_view_projects_the_centre_to_the_centre,
test_clip_planes_bracket_the_mesh,
test_pose_matrix_is_orthonormal_and_looks_at_the_centre,
diff --git a/workers/texture/texture_projection.py b/workers/texture/texture_projection.py
index 1c6139ae7..43a596718 100644
--- a/workers/texture/texture_projection.py
+++ b/workers/texture/texture_projection.py
@@ -32,7 +32,10 @@ from __future__ import annotations
import math
from typing import Optional, Sequence
+import io
+
import numpy as np
+from PIL import Image
# Confidence falls off as cos(angle between the surface normal and the direction
# to the camera) ** FACING_EXPONENT. A view that sees a texel head on should win
@@ -56,6 +59,43 @@ MIN_FACING = 0.12
# the slope-scaled bias in project_views_to_uv.
DEPTH_TOLERANCE_FRAC = 0.01
+# Work budgets. The UV rasterizer walks triangles in python, so its cost is
+# linear in face count, and a decoded image costs width * height * channels
+# whatever its compressed size. Both inputs come from a caller-supplied URL or
+# payload, so each is bounded here rather than trusted.
+MAX_MESH_FACES = 500_000
+MAX_DECODED_PIXELS = 64_000_000
+
+# Pillow only warns at this limit and errors at twice it; setting it makes the
+# library's own check part of the same budget for every decode in the process.
+Image.MAX_IMAGE_PIXELS = MAX_DECODED_PIXELS
+
+
+def assert_face_budget(face_count: int) -> None:
+ if face_count > MAX_MESH_FACES:
+ raise ValueError(
+ f"mesh has {face_count} faces, over the {MAX_MESH_FACES} face limit"
+ )
+
+
+def open_bounded_image(data: bytes) -> Image.Image:
+ """Open an image after checking its declared size against the pixel budget.
+
+ Image.open reads only the header, so the check costs nothing and happens
+ before any pixel is decoded.
+ """
+ try:
+ img = Image.open(io.BytesIO(data))
+ except Image.DecompressionBombError as exc:
+ raise ValueError("image exceeds the decoded pixels limit") from exc
+ width, height = img.size
+ if width * height > MAX_DECODED_PIXELS:
+ raise ValueError(
+ f"image is {width}x{height}, over the {MAX_DECODED_PIXELS} decoded pixels limit"
+ )
+ return img
+
+
_WORLD_UP = np.array([0.0, 1.0, 0.0])
_WORLD_UP_FALLBACK = np.array([0.0, 0.0, 1.0])