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(cad-forge): open artifacts with O_NOFOLLOW and reject frame and generator attribute escapes

nirholasa1c319fb59f7
diff --git a/workers/cad-forge/cad_policy.py b/workers/cad-forge/cad_policy.py
index 71776bef2..3ceb3b540 100644
--- a/workers/cad-forge/cad_policy.py
+++ b/workers/cad-forge/cad_policy.py
@@ -57,6 +57,18 @@ BANNED_NAMES = frozenset({
# Attribute names that perform attribute lookups from inside a string.
BANNED_ATTRIBUTES = frozenset({"format", "format_map", "vformat", "mro"})
+# Frame, code, generator, coroutine and traceback internals. None start with an
+# underscore, yet `gen.gi_frame.f_back.f_globals` walks from a harmless generator
+# to the sandbox runner's globals and the real builtins.
+INTROSPECTION_ATTRIBUTES = frozenset({
+ "f_back", "f_builtins", "f_code", "f_globals", "f_locals", "f_trace",
+ "gi_frame", "gi_code", "gi_yieldfrom", "gi_running", "gi_suspended",
+ "cr_frame", "cr_code", "cr_await", "cr_origin", "cr_running",
+ "ag_frame", "ag_code", "ag_await", "ag_running",
+ "tb_frame", "tb_next", "tb_lasti", "tb_lineno",
+})
+INTROSPECTION_PREFIXES = ("co_", "gi_", "cr_", "ag_", "tb_")
+
SAFE_BUILTIN_NAMES = (
"abs", "all", "any", "bool", "dict", "divmod", "enumerate", "filter",
"float", "frozenset", "hasattr", "int", "isinstance", "iter", "len", "list",
@@ -129,6 +141,8 @@ def check_source(source: str) -> ast.Module:
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 node.attr in BANNED_ATTRIBUTES:
raise PolicyViolation(f"'.{node.attr}' is not available; use an f-string instead.", line)
elif isinstance(node, ast.Name):
@@ -136,6 +150,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)
+ 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)):
raise PolicyViolation("async code is not allowed.", line)
elif isinstance(node, (ast.FunctionDef, ast.ClassDef)):
diff --git a/workers/cad-forge/main.py b/workers/cad-forge/main.py
index 31d328dbf..25199b03a 100644
--- a/workers/cad-forge/main.py
+++ b/workers/cad-forge/main.py
@@ -34,6 +34,7 @@ import os
import re
import resource
import signal
+import stat
import shutil
import subprocess
import sys
@@ -214,10 +215,21 @@ def _collect(child: Child, result: dict) -> dict:
artifacts = {}
total = 0
for name in result.get("files", []):
+ if name not in ARTIFACT_KEYS:
+ continue
path = os.path.join(child.workdir, name)
- if name not in ARTIFACT_KEYS or not os.path.isfile(path):
+ # The workdir belongs to the unprivileged child, so a name can be a
+ # symlink to a file only the parent may read. O_NOFOLLOW refuses it, and
+ # fstat on the opened descriptor sizes the real file, not the link.
+ try:
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ except OSError:
continue
- total += os.path.getsize(path)
+ with os.fdopen(fd, "rb") as fh:
+ if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
+ continue
+ data = fh.read(MAX_ARTIFACT_BYTES + 1)
+ total += len(data)
if total > MAX_ARTIFACT_BYTES:
return {
"ok": False,
@@ -225,8 +237,7 @@ def _collect(child: Child, result: dict) -> dict:
"log": result.get("log", ""),
"elapsed_s": result.get("elapsed_s"),
}
- with open(path, "rb") as fh:
- artifacts[ARTIFACT_KEYS[name]] = base64.b64encode(fh.read()).decode("ascii")
+ artifacts[ARTIFACT_KEYS[name]] = base64.b64encode(data).decode("ascii")
result["artifacts"] = artifacts
result.pop("files", None)
return result
diff --git a/workers/cad-forge/sandbox_child.py b/workers/cad-forge/sandbox_child.py
index 66bfa208d..cc94ac17c 100644
--- a/workers/cad-forge/sandbox_child.py
+++ b/workers/cad-forge/sandbox_child.py
@@ -52,6 +52,7 @@ SECCOMP_DENY = (
"process_vm_writev", "unshare", "setns", "mount", "umount2", "pivot_root",
"chroot", "keyctl", "add_key", "request_key", "bpf", "perf_event_open",
"userfaultfd", "personality", "kexec_load", "init_module", "finit_module",
+ "symlink", "symlinkat", "link", "linkat",
)
diff --git a/workers/cad-forge/test_cad_policy.py b/workers/cad-forge/test_cad_policy.py
index 96e066cf8..a6dfac7f2 100644
--- a/workers/cad-forge/test_cad_policy.py
+++ b/workers/cad-forge/test_cad_policy.py
@@ -103,6 +103,19 @@ class PolicyTests(unittest.TestCase):
self.assertNotIn(name, table)
self.assertIs(table["__import__"], guarded_import)
+ def test_refuses_frame_and_generator_introspection(self):
+ for attr in ("gi_frame", "f_back", "f_globals", "f_builtins", "f_locals",
+ "gi_code", "cr_frame", "tb_frame", "tb_next", "co_consts"):
+ self.assertRefused(f"x = y.{attr}", f"'.{attr}'")
+ self.assertRefused("g = (i for i in range(1))\nx = g.gi_frame.f_back.f_globals\n", "is not allowed")
+
+ def test_refuses_yield(self):
+ self.assertRefused("def g():\n yield 1\n", "yield")
+ self.assertRefused("def g():\n yield from range(2)\n", "yield")
+
+ 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")
+
if __name__ == "__main__":
unittest.main(verbosity=1)
diff --git a/workers/cad-forge/test_sandbox.py b/workers/cad-forge/test_sandbox.py
index 892b4b879..c36775e3b 100644
--- a/workers/cad-forge/test_sandbox.py
+++ b/workers/cad-forge/test_sandbox.py
@@ -8,6 +8,7 @@ real escape attempts against each isolation layer. Runs in the Docker build
import base64
import os
+import shutil
import subprocess
import sys
import textwrap
@@ -251,5 +252,26 @@ class IsolationLayerTests(unittest.TestCase):
self.assertNotEqual(results["parent_env"], "read")
+class CollectTests(unittest.TestCase):
+ def test_collect_does_not_follow_symlinked_artifacts(self):
+ import tempfile
+
+ secret = tempfile.NamedTemporaryFile(delete=False)
+ secret.write(b"parent-only-secret")
+ secret.close()
+ workdir = tempfile.mkdtemp(prefix="cad-collect-")
+ try:
+ os.symlink(secret.name, os.path.join(workdir, "part.glb"))
+ with open(os.path.join(workdir, "part.stl"), "wb") as fh:
+ fh.write(b"solid")
+ child = main.Child(proc=None, workdir=workdir, started=0.0)
+ out = main._collect(child, {"ok": True, "files": ["part.glb", "part.stl"]})
+ self.assertNotIn("glb", out["artifacts"])
+ self.assertEqual(base64.b64decode(out["artifacts"]["stl"]), b"solid")
+ finally:
+ os.unlink(secret.name)
+ shutil.rmtree(workdir, ignore_errors=True)
+
+
if __name__ == "__main__":
unittest.main(verbosity=2)