Skip to content

Official Codebase of 3DCodeVerse

Python

harden the generated-code boundary: env scrub, name validation, symlink containment

gaoypeng4c5b84a9c92e
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
index 9c09fc6a..d67d510d 100644
--- a/harness/codeverse/contracts/agent.py
+++ b/harness/codeverse/contracts/agent.py
@@ -1,4 +1,10 @@
-"""CodingAgent job/result — one headless agentic session on a workspace."""
+"""CodingAgent job/result — one headless agentic session on a workspace.
+
+Trust model (cooperative, by design): generated code and agent sessions run with local
+filesystem access and no network sandbox; the mitigation is that secrets are scrubbed
+from their environment (``codeverse.proc.scrub_secrets`` for the generated-code
+runtimes, ``agents/cli_common.hardened_env`` for the coding-agent CLIs).
+"""
from __future__ import annotations
@@ -41,7 +47,6 @@ class AgentJob(BaseModel):
label: str = ""
timeout_s: int = 1800
max_turns: int = 60
- allow_network: bool = False
spatial_tools: bool = Field(
default=True, description="expose the 3dcv MCP spatial tools to the agent"
)
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
index 16ff6d8d..a89cece2 100644
--- a/harness/codeverse/contracts/plan.py
+++ b/harness/codeverse/contracts/plan.py
@@ -10,9 +10,10 @@ plans are re-asked with the validation errors, before any generator runs.
from __future__ import annotations
import math
+import re
from typing import Literal
-from pydantic import BaseModel, Field, model_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from codeverse.contracts.common import Vec3
from codeverse.conventions import to_snake
@@ -382,13 +383,28 @@ class EffectPlan(BaseModel):
target: str = Field(default="", description="zone / asset / scene it applies to")
+#: a camera name becomes a render FILENAME (``render_scene.mjs`` writes ``<name>_<t>.png``);
+#: the charset ``render_glb.mjs`` already enforces for view names, plus a length bound.
+CAMERA_NAME_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
+
+
class CameraPlan(BaseModel):
- name: str
+ name: str = Field(description="letters/digits/_/- only; it becomes a render filename")
position: Vec3
look_at: Vec3
fov: float = 50.0
purpose: str = ""
+ @field_validator("name")
+ @classmethod
+ def _filename_safe(cls, v: str) -> str:
+ """Reject (never mangle) unsafe names — the planner is re-asked with the error."""
+ if not CAMERA_NAME_RE.fullmatch(v):
+ raise ValueError(
+ f"camera name {v!r} must match [A-Za-z0-9_-]{{1,64}}: it becomes a render "
+ "filename (no spaces, dots, slashes or other path characters)")
+ return v
+
class ScenePlan(BaseModel):
title: str
diff --git a/harness/codeverse/languages/blender/runtime.py b/harness/codeverse/languages/blender/runtime.py
index ec1d0ef2..105e22da 100644
--- a/harness/codeverse/languages/blender/runtime.py
+++ b/harness/codeverse/languages/blender/runtime.py
@@ -26,6 +26,7 @@ from codeverse.languages._common import (
)
from codeverse.languages.blender.layout import ENTRY_REL, lint_workspace, part_file_rel
from codeverse.languages.blender.skeleton import write_blender_skeleton
+from codeverse.proc import scrub_secrets
from codeverse.prompts import PROMPTS_DIR
from codeverse.workspace import Workspace
@@ -39,8 +40,10 @@ class BlenderNotFoundError(RuntimeError):
def blender_env() -> dict[str, str]:
"""Environment for a headless Blender child: keep the user's env but make sure the
- host python (conda) cannot leak into Blender's bundled interpreter."""
- env = dict(os.environ)
+ host python (conda) cannot leak into Blender's bundled interpreter, and strip
+ credential-shaped vars (:func:`codeverse.proc.scrub_secrets`) — the model-authored
+ ``model.py`` executes inside this process and must never see API keys."""
+ env = scrub_secrets(dict(os.environ))
for k in ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"):
env.pop(k, None)
env["PYTHONNOUSERSITE"] = "1"
diff --git a/harness/codeverse/languages/cadquery/runtime.py b/harness/codeverse/languages/cadquery/runtime.py
index 6e7068bb..b1527c00 100644
--- a/harness/codeverse/languages/cadquery/runtime.py
+++ b/harness/codeverse/languages/cadquery/runtime.py
@@ -18,6 +18,7 @@ from codeverse.conventions import MAX_TRIS_OBJECT
from codeverse.languages._common import compose_build_result, remove_stale, run_subprocess
from codeverse.languages.cadquery.lint import lint_cadquery_file
from codeverse.languages.cadquery.skeleton import write_cadquery_skeleton
+from codeverse.proc import scrub_secrets
from codeverse.prompts import PROMPTS_DIR
from codeverse.workspace import Workspace
@@ -26,7 +27,10 @@ WRAPPER = _PKG_DIR / "wrappers" / "run_cq.py"
def cadquery_env() -> dict[str, str]:
- env = dict(os.environ)
+ """Environment for the wrapper subprocess that executes the model-authored
+ ``src/model.py``: the user's env minus credential-shaped vars
+ (:func:`codeverse.proc.scrub_secrets`)."""
+ env = scrub_secrets(dict(os.environ))
env.pop("PYTHONSTARTUP", None)
env.setdefault("OMP_NUM_THREADS", "4")
env.setdefault("PYTHONUNBUFFERED", "1")
diff --git a/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py b/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py
index cc013f77..ee9a55e5 100644
--- a/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py
+++ b/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py
@@ -39,6 +39,18 @@ def _snake(name: str) -> str:
return re.sub(r"_+", "_", s).strip("_").lower()
+#: link names double as ``meshes/<link>.glb`` filename stems: plain identifiers only.
+#: The lint layer states the same rule (``languages/urdf/lint._IDENT``) but only WARNs,
+#: so the wrapper enforces it — ``../evil`` must be a build error, never a file written
+#: outside ``meshes/``.
+_SAFE_LINK = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
+
+
+def _bad_links(links: list[str]) -> list[str]:
+ """Link names that are unsafe as filenames (not plain identifiers)."""
+ return [name for name in links if not _SAFE_LINK.fullmatch(name or "")]
+
+
def _set_rlimit(gb: float) -> None:
try:
import resource
@@ -195,6 +207,14 @@ def main() -> None:
build.update(error_type="UrdfParseError", error_message=str(e), error_file="src/robot.urdf")
finish()
return
+ bad = _bad_links(links)
+ if bad:
+ build.update(error_type="UnsafeLinkName", error_file="src/robot.urdf",
+ error_message="URDF link name(s) unusable as meshes/<link>.glb filenames "
+ "(must match [A-Za-z][A-Za-z0-9_]*): "
+ + ", ".join(repr(b) for b in bad))
+ finish()
+ return
bpy.ops.wm.read_factory_settings(use_empty=True)
err = _exec_script(script)
diff --git a/harness/codeverse/proc.py b/harness/codeverse/proc.py
index 8700fd72..90478610 100644
--- a/harness/codeverse/proc.py
+++ b/harness/codeverse/proc.py
@@ -117,6 +117,35 @@ def kill_group(proc: subprocess.Popen[str]) -> None:
proc.kill()
+# ------------------------------------------------------------------ env scrubbing
+#: COPY of the credential patterns in ``agents/cli_common.is_secret_env`` (its sibling —
+#: keep the two in sync; tests/core/test_proc.py pins them together). Duplicated because
+#: proc.py imports nothing from ``codeverse``: the agents package sits above this layer.
+_SECRET_EXACT: frozenset[str] = frozenset({
+ "GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
+ "OPENAI_ORG_ID", "HF_TOKEN", "HUGGINGFACE_TOKEN", "GITHUB_TOKEN", "GH_TOKEN",
+ "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "SUPABASE_SERVICE_ROLE_KEY", "CODEX_API_KEY",
+})
+_SECRET_SUFFIXES: tuple[str, ...] = (
+ "_API_KEY", "_SECRET", "_SECRET_KEY", "_TOKEN", "_AUTH_TOKEN", "_PASSWORD", "_PRIVATE_KEY",
+)
+
+
+def scrub_secrets(env: dict[str, str]) -> dict[str, str]:
+ """``env`` minus credential-shaped variables (exact names + ``*_API_KEY``-style suffixes).
+
+ Model-generated code runs in subprocesses that inherit the harness environment
+ (blender, the cadquery python, node) and nothing generated ever legitimately needs
+ a credential — so the keys must not be there to leak into logs, artifacts or child
+ processes. Everything else (PATH, HOME, DISPLAY, MESA_*/GALLIUM_* render config...)
+ passes through untouched.
+ """
+ return {
+ k: v for k, v in env.items()
+ if k not in _SECRET_EXACT and not k.endswith(_SECRET_SUFFIXES)
+ }
+
+
def tail(text: str, *, max_lines: int = 40, max_chars: int = 4000) -> str:
"""Last ``max_lines`` lines of ``text``, capped at ``max_chars`` characters."""
lines = text.splitlines()[-max_lines:]
diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.py
index 4d646412..47319b3f 100644
--- a/harness/codeverse/spatial/node.py
+++ b/harness/codeverse/spatial/node.py
@@ -22,7 +22,7 @@ from pathlib import Path
from typing import Any
from codeverse.config import get_settings
-from codeverse.proc import run_subprocess
+from codeverse.proc import run_subprocess, scrub_secrets
TAIL_CHARS = 4000
@@ -184,7 +184,9 @@ def run_node(
cmd += ["--import", str(three_import_hook())]
cmd += [str(script), *(args or [])]
- env = dict(os.environ)
+ # node runs harness drivers AND model-generated code (scene.js, agent modules):
+ # credential-shaped vars are stripped; env_extra (harness-owned) is applied after.
+ env = scrub_secrets(dict(os.environ))
env["NODE_PATH"] = str(node_modules_dir())
env.setdefault("CV3D_CACHE_DIR", str(settings.cache_dir))
env.setdefault("NODE_OPTIONS", "")
diff --git a/harness/runtime_js/lib/cli.mjs b/harness/runtime_js/lib/cli.mjs
index 23fa621f..6b97a482 100644
--- a/harness/runtime_js/lib/cli.mjs
+++ b/harness/runtime_js/lib/cli.mjs
@@ -50,6 +50,15 @@ export function dataUrlToPng(dataUrl, outPath) {
fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
}
+/** A name used as a filename component (cameras, views): [A-Za-z0-9_-]{1,64} or throw. */
+export function safeName(name, label = 'name') {
+ const s = String(name);
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(s)) {
+ throw new Error(`unsafe ${label}: ${JSON.stringify(name)} (must match [A-Za-z0-9_-]{1,64})`);
+ }
+ return s;
+}
+
/** Wall-clock guard: kills the process if the driver exceeds its budget. */
export function armWatchdog(ms, onFire) {
const t = setTimeout(() => {
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index 863685e6..6044daf4 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -93,7 +93,12 @@ function validateCameras(raw) {
const fov = Number.isFinite(c.fov) ? c.fov : 50;
if (fov < 5 || fov > 150) problems.push(`cameras[${i}] fov ${fov} outside [5,150]`);
if (p.every((x, k) => Math.abs(x - l[k]) < 1e-6)) problems.push(`cameras[${i}] position equals lookAt`);
- out.push({ name: String(c.name || `cam_${i}`), position: p.map(Number), lookAt: l.map(Number), fov });
+ const name = String(c.name || `cam_${i}`);
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) {
+ problems.push(`cameras[${i}] name ${JSON.stringify(name)} must match [A-Za-z0-9_-]{1,64} — it becomes a render filename`);
+ return;
+ }
+ out.push({ name, position: p.map(Number), lookAt: l.map(Number), fov });
});
if (out.length === 0) problems.push('no valid cameras (author 1-6 {name, position, lookAt, fov})');
if (out.length > 6) problems.push(`too many cameras (${out.length} > 6)`);
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
index 451c213b..66e8a91a 100644
--- a/harness/runtime_js/render_scene.mjs
+++ b/harness/runtime_js/render_scene.mjs
@@ -15,7 +15,7 @@
*/
import path from 'node:path';
-import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, writeJson } from './lib/cli.mjs';
+import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';
import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
import { fitOrbitCameras, framingBox } from './lib/orbit.mjs';
@@ -31,6 +31,13 @@ function tag(t) {
return 't' + t.toFixed(2).replace(/0+$/, '').replace(/\.$/, '').replace('.', 'p');
}
+/** outDir-contained path for a view file; refuses any name that escapes outDir. */
+function outFile(outDir, file) {
+ const p = path.resolve(outDir, file);
+ if (!p.startsWith(outDir + path.sep)) throw new Error(`unsafe output path: ${file}`);
+ return p;
+}
+
async function main() {
if (!args.ws || !args.out) throw new Error('--ws and --out are required');
const width = parseInt(args.width, 10), height = parseInt(args.height, 10);
@@ -72,6 +79,8 @@ async function main() {
metrics.framing_bbox = bbox;
cams.push(...fitOrbitCameras(bbox, views, { aspect: width / height, groundY: metrics.census.ground_y, noFog: !args['orbit-fog'] }));
}
+ // camera names become filenames: reject path tricks before composing any output path
+ for (const c of cams) c.name = safeName(c.name, 'camera name');
const seen = new Set();
cams = cams.filter((c) => { const k = c.name; if (seen.has(k)) return false; seen.add(k); return true; });
if (!cams.length) throw new Error('no cameras to render (authored list empty and no orbit views)');
@@ -94,12 +103,12 @@ async function main() {
try {
const r = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt), c, t);
const file = `${c.name}_${tag(t)}.png`;
- dataUrlToPng(r.dataUrl, path.join(outDir, file));
+ dataUrlToPng(r.dataUrl, outFile(outDir, file));
metrics.views.push({ name: c.name, kind: c.kind, path: file, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: r.ms });
if (args.counterfactual) {
const cf = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt, { stripCustom: true }), c, t);
const cfFile = `${c.name}_${tag(t)}_nocustom.png`;
- dataUrlToPng(cf.dataUrl, path.join(outDir, cfFile));
+ dataUrlToPng(cf.dataUrl, outFile(outDir, cfFile));
metrics.views.push({ name: `${c.name}_nocustom`, kind: 'counterfactual', path: cfFile, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: cf.ms, counterfactual_of: file });
}
} catch (e) { sceneErr(`render failed for '${c.name}' at t=${t}`, e); }
diff --git a/harness/runtime_js/serve.cjs b/harness/runtime_js/serve.cjs
index 5d06a58a..7eb48fb5 100644
--- a/harness/runtime_js/serve.cjs
+++ b/harness/runtime_js/serve.cjs
@@ -56,7 +56,22 @@ function mimeFor(file) {
return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
}
-/** Resolve a URL path inside `rootAbs`; null when it escapes the root or is not a file. */
+// realpath of each served root, cached (computed once per root per process).
+const REAL_ROOTS = new Map();
+function realRoot(rootAbs) {
+ let real = REAL_ROOTS.get(rootAbs);
+ if (!real) {
+ real = fs.realpathSync(rootAbs);
+ REAL_ROOTS.set(rootAbs, real);
+ }
+ return real;
+}
+
+/** Resolve a URL path inside `rootAbs`; null when it escapes the root or is not a file.
+ * Lexical containment first, then realpath containment: statSync follows symlinks, so a
+ * symlink inside the root pointing outside would otherwise be served (workspace content
+ * is model-authored). In-root symlinks (workspace aliases, node_modules/.bin) still
+ * resolve inside the root and keep working. */
function resolveInside(rootAbs, relUrlPath) {
const abs = path.resolve(rootAbs, '.' + path.posix.normalize('/' + relUrlPath));
if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) return null;
@@ -66,7 +81,15 @@ function resolveInside(rootAbs, relUrlPath) {
} catch (_e) {
return null;
}
- return st.isFile() ? abs : null;
+ if (!st.isFile()) return null;
+ try {
+ const real = fs.realpathSync(abs);
+ const rootReal = realRoot(rootAbs);
+ if (real !== rootReal && !real.startsWith(rootReal + path.sep)) return null;
+ } catch (_e) {
+ return null;
+ }
+ return abs;
}
/**
diff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.py
index 98b715d9..f20fd90f 100644
--- a/harness/tests/blender_cadquery/test_blender_runtime.py
+++ b/harness/tests/blender_cadquery/test_blender_runtime.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import json
-import os
import stat
import time
from pathlib import Path
@@ -62,16 +61,18 @@ def test_missing_entry_file(tmp_ws, tmp_path) -> None:
assert not r.ok and r.error_type == "MissingEntryFile"
-def test_build_command_and_env(tmp_ws, tmp_path) -> None:
+def test_build_command_and_env(tmp_ws, tmp_path, monkeypatch) -> None:
rt = BlenderRuntime(blender=_fake_blender(tmp_path))
cmd = rt.build_command(tmp_ws, stl=True, seed=3, tri_limit=1000)
assert cmd[1:5] == ["-b", "--factory-startup", "--python", str(WRAPPER)] and "--" in cmd
assert cmd[cmd.index("--script") + 1] == str(tmp_ws.src / "model.py") and "--stl" in cmd and "--seed" in cmd
- os.environ["PYTHONPATH"] = "/tmp/x"
- try:
- assert "PYTHONPATH" not in blender_env() and blender_env()["PYTHONNOUSERSITE"] == "1"
- finally:
- del os.environ["PYTHONPATH"]
+ monkeypatch.setenv("PYTHONPATH", "/tmp/x")
+ monkeypatch.setenv("GEMINI_API_KEYS", "k1,k2")
+ monkeypatch.setenv("SOME_SERVICE_TOKEN", "t")
+ env = blender_env()
+ assert "PYTHONPATH" not in env and env["PYTHONNOUSERSITE"] == "1"
+ # model-authored model.py runs inside blender: credentials scrubbed, PATH/HOME kept
+ assert "GEMINI_API_KEYS" not in env and "SOME_SERVICE_TOKEN" not in env and "PATH" in env
def test_build_with_fake_blender(tmp_ws, tmp_path) -> None:
diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.py
index c451550c..cf78076e 100644
--- a/harness/tests/blender_cadquery/test_cadquery_runtime.py
+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py
@@ -15,7 +15,7 @@ import pytest
from codeverse.languages import get_runtime
from codeverse.languages.base import LanguageRuntime
from codeverse.languages.cadquery.lint import lint_cadquery_source
-from codeverse.languages.cadquery.runtime import WRAPPER, CadQueryRuntime
+from codeverse.languages.cadquery.runtime import WRAPPER, CadQueryRuntime, cadquery_env
from codeverse.languages.cadquery.skeleton import cadquery_skeleton_source
from tests.blender_cadquery.conftest import has_cadquery
@@ -208,3 +208,14 @@ result.add(cq.Workplane("XY").box(0.02, 0.02, 0.02).edges("|Z"), name="Leg")
r = rt.build(tmp_ws, timeout_s=120)
assert r.ok and r.census["parts"][0]["n_solids"] == 0
assert any("'Sheet'" in w and "contains no solid" in w for w in r.census["build_report"]["warnings"])
+
+
+def test_cadquery_env_scrubs_secrets(monkeypatch) -> None:
+ """src/model.py executes under this env: credential-shaped vars must not reach it."""
+ monkeypatch.setenv("GEMINI_API_KEYS", "k")
+ monkeypatch.setenv("FOO_API_KEY", "x")
+ monkeypatch.setenv("PYTHONSTARTUP", "/tmp/s")
+ env = cadquery_env()
+ assert "GEMINI_API_KEYS" not in env and "FOO_API_KEY" not in env
+ assert "PYTHONSTARTUP" not in env
+ assert env["OMP_NUM_THREADS"] == "4" and "PATH" in env
diff --git a/harness/tests/core/test_contracts.py b/harness/tests/core/test_contracts.py
index eb368eed..0c96adbe 100644
--- a/harness/tests/core/test_contracts.py
+++ b/harness/tests/core/test_contracts.py
@@ -92,6 +92,15 @@ def test_scene_plan_zone_contents_must_be_assets():
assert ok.zones[0].contents == ["Lantern"]
+def test_camera_plan_name_must_be_filename_safe():
+ """Camera names become render filenames (render_scene.mjs) — reject path tricks."""
+ ok = CameraPlan(name="pier_low-2", position=(0, 1.6, 5), look_at=(0, 0, 0))
+ assert ok.name == "pier_low-2"
+ for bad in ("x/../y", "/absolute", "a\\b", "a b", "a.png", "", "x" * 200):
+ with pytest.raises(ValidationError):
+ CameraPlan(name=bad, position=(0, 1.6, 5), look_at=(0, 0, 0))
+
+
def test_chat_message_helpers():
m = ChatMessage.user("hi")
assert m.text == "hi" and m.role == "user"
diff --git a/harness/tests/core/test_proc.py b/harness/tests/core/test_proc.py
index cd3e0476..465e31f4 100644
--- a/harness/tests/core/test_proc.py
+++ b/harness/tests/core/test_proc.py
@@ -18,6 +18,7 @@ from codeverse.proc import (
read_json_or_none,
read_jsonl_lenient,
run_subprocess,
+ scrub_secrets,
tail,
write_json_atomic,
)
@@ -267,3 +268,33 @@ def test_jsonl_helpers_round_trip_and_skip_bad_lines(tmp_path: Path):
rows = read_jsonl_lenient(p)
assert rows == [{"k": "é", "p": str(tmp_path)}, [1, 2]]
assert read_jsonl_lenient(p, dicts_only=True) == rows[:1]
+
+
+# --------------------------------------------------------------------------- scrub_secrets
+def test_scrub_secrets_drops_credential_shaped_vars():
+ env = {
+ "GEMINI_API_KEYS": "k1,k2", "GEMINI_API_KEY": "k", "FOO_API_KEY": "x",
+ "MY_SERVICE_TOKEN": "t", "DB_PASSWORD": "p", "DEPLOY_PRIVATE_KEY": "s",
+ "AWS_SECRET_ACCESS_KEY": "a", "CLIENT_SECRET": "c", "X_AUTH_TOKEN": "z",
+ }
+ assert scrub_secrets(env) == {}
+
+
+def test_scrub_secrets_keeps_everything_generated_code_needs():
+ env = {"PATH": "/usr/bin", "HOME": "/home/u", "DISPLAY": ":0", "NODE_PATH": "/nm",
+ "MESA_LOADER_DRIVER_OVERRIDE": "d3d12", "GALLIUM_DRIVER": "llvmpipe",
+ "CV3D_RENDER_GPU": "off", "PYTHONUNBUFFERED": "1",
+ "TOKENIZERS_PARALLELISM": "false"} # _TOKEN is a SUFFIX match, not a substring
+ assert scrub_secrets(dict(env)) == env
+
+
+def test_scrub_secrets_stays_in_sync_with_agents_cli_common():
+ """proc.scrub_secrets is a COPY of agents/cli_common.is_secret_env (proc.py must
+ stay stdlib-only) — this pins the two pattern sets together."""
+ from codeverse.agents.cli_common import is_secret_env
+ from codeverse.proc import _SECRET_EXACT, _SECRET_SUFFIXES
+
+ probes = (sorted(_SECRET_EXACT) + [f"X{s}" for s in _SECRET_SUFFIXES]
+ + ["PATH", "HOME", "NODE_PATH", "TOKENIZERS_PARALLELISM"])
+ for name in probes:
+ assert is_secret_env(name) == (name not in scrub_secrets({name: "v"})), name
diff --git a/harness/tests/threejs_render/test_node.py b/harness/tests/threejs_render/test_node.py
index 494e3ea3..fdaa77b1 100644
--- a/harness/tests/threejs_render/test_node.py
+++ b/harness/tests/threejs_render/test_node.py
@@ -61,3 +61,17 @@ def test_three_hook_resolves_bare_three(tmp_path: Path):
res = run_node(script, [], timeout_s=30, three_hook=True)
assert res.last_json["rev"] == "182" and res.last_json["rb"] == "function"
assert (runtime_js_dir() / "lib" / "resolve_three.mjs").is_file()
+
+
+def test_run_node_env_is_scrubbed_of_secrets(tmp_path: Path, monkeypatch):
+ """Generated js (scene.js, agent modules) runs under run_node: no credentials."""
+ monkeypatch.setenv("GEMINI_API_KEYS", "k1,k2")
+ monkeypatch.setenv("FAKE_SERVICE_TOKEN", "t")
+ script = tmp_path / "env.mjs"
+ script.write_text(
+ "console.log(JSON.stringify({ok: true, gem: process.env.GEMINI_API_KEYS ?? null, "
+ "tok: process.env.FAKE_SERVICE_TOKEN ?? null, np: process.env.NODE_PATH ?? null}));")
+ rec = run_node(script, [], timeout_s=20).last_json
+ assert rec["gem"] is None and rec["tok"] is None
+ assert rec["np"] and rec["np"].endswith("node_modules")
diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.py
index 13f9230a..d45af58e 100644
--- a/harness/tests/threejs_render/test_runtime_js.py
+++ b/harness/tests/threejs_render/test_runtime_js.py
@@ -172,3 +172,44 @@ const {{ launchBrowser }} = require({json.dumps(str(runtime_js_dir() / 'gpu_laun
off = run_node(script, [], timeout_s=120, env_extra={**env, "CV3D_BROWSER_REUSE": "off"}).last_json
assert off["a_shared"] is False and off["b_shared"] is False
_reap_daemons(tmp_path / "cache")
+
+
+def test_serve_refuses_symlinks_that_escape_the_root(tmp_path: Path):
+ """resolveInside is lexical + realpath: a symlink inside the workspace pointing
+ outside must 404 (workspace content is model-authored); in-root symlinks and
+ plain files keep serving."""
+ root = tmp_path / "root"
+ root.mkdir()
+ (root / "ok.txt").write_text("fine")
+ (tmp_path / "secret.txt").write_text("s3cr3t")
+ (root / "inside.txt").symlink_to(root / "ok.txt")
+ (root / "leak.txt").symlink_to(tmp_path / "secret.txt")
+ (root / "dirlink").symlink_to(tmp_path)
+ script = tmp_path / "s.cjs"
+ script.write_text(f"""
+const {{ serveDirs }} = require({json.dumps(str(runtime_js_dir() / 'serve.cjs'))});
+(async () => {{
+ const srv = await serveDirs({{ root: {json.dumps(str(root))} }});
+ const get = async (p) => (await fetch(srv.url(p))).status;
+ const out = {{ ok: await get('/ok.txt'), inside: await get('/inside.txt'),
+ leak: await get('/leak.txt'), dirleak: await get('/dirlink/secret.txt') }};
+ await srv.close();
+ console.log(JSON.stringify(out));
+}})().catch((e) => {{ console.error(e); process.exit(1); }});
+""")
+ out = run_node(script, [], timeout_s=60).last_json
+ assert out == {"ok": 200, "inside": 200, "leak": 404, "dirleak": 404}
+
+
+def test_cli_safe_name_rejects_path_tricks(tmp_path: Path):
+ """lib/cli.mjs safeName guards every filename composed from a camera/view name."""
+ script = tmp_path / "n.mjs"
+ cli = (runtime_js_dir() / "lib" / "cli.mjs").as_uri()
+ script.write_text(f"""
+const {{ safeName }} = await import({json.dumps(cli)});
+const rejects = (v) => {{ try {{ safeName(v); return false; }} catch {{ return true; }} }};
+const bad = ['x/../y', '/abs', 'a\\\\b', 'a b', 'a.png', '', 'x'.repeat(200)];
+console.log(JSON.stringify({{ ok: true, good: safeName('cam_a-1'), all_rejected: bad.every(rejects) }}));
+""")
+ out = run_node(script, [], timeout_s=30).last_json
+ assert out == {"ok": True, "good": "cam_a-1", "all_rejected": True}
diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.py
index 6c53ad7e..cf17e1f4 100644
--- a/harness/tests/urdf_joints/test_live_blender.py
+++ b/harness/tests/urdf_joints/test_live_blender.py
@@ -113,3 +113,27 @@ def test_script_error_and_missing_object(tmp_path, cabinet_plan):
m.write_text(m.read_text().replace("raise RuntimeError('boom')\n", "").replace("'handle'", "'Handle'"))
res = rt.build(ws)
assert not res.ok and res.error_type == "MissingLinkObjects" and "Handle" in res.error_message
+
+
+@needs_blender
+def test_wrapper_unsafe_link_name_is_a_build_error(tmp_path):
+ """End-to-end: a traversal-shaped URDF link name fails the build before the agent
+ script runs; meshes/ is never created, nothing lands outside it."""
+ import json as _json
+ import subprocess
+
+ from codeverse.languages.urdf.runtime import WRAPPER
+
+ (tmp_path / "robot.urdf").write_text('<robot name="r"><link name="../evil"/></robot>')
+ (tmp_path / "model.py").write_text("import bpy\n")
+ out = tmp_path / "art"
+ blender = get_settings().resolve_blender()
+ subprocess.run(
+ [blender, "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"),
+ "--out", str(out)],
+ capture_output=True, text=True, timeout=180, check=False)
+ build = _json.loads((out / "build.json").read_text())
+ assert not build["ok"] and build["error_type"] == "UnsafeLinkName"
+ assert "../evil" in build["error_message"]
+ assert not (out / "meshes").exists() and not (tmp_path / "evil.glb").exists()
diff --git a/harness/tests/urdf_joints/test_runtime_offline.py b/harness/tests/urdf_joints/test_runtime_offline.py
index 321c0628..61314163 100644
--- a/harness/tests/urdf_joints/test_runtime_offline.py
+++ b/harness/tests/urdf_joints/test_runtime_offline.py
@@ -119,3 +119,23 @@ def test_build_timeout(tmp_path, cabinet_plan, fake_blender, monkeypatch):
ws = _ws(tmp_path, cabinet_plan)
res = UrdfBlenderRuntime().build(ws, timeout_s=1)
assert not res.ok and res.error_type == "Timeout"
+
+
+def test_wrapper_rejects_unsafe_link_names_offline():
+ """run_bpy_links refuses link names that are not plain identifiers — ``../evil``
+ must be a build error, never a ``meshes/<link>.glb`` write outside meshes/. The
+ wrapper needs bpy, so its pure name check is exec'd out of the source."""
+ import ast
+ import re as _re
+
+ src = rt_mod.WRAPPER.read_text()
+ assert "UnsafeLinkName" in src and "_bad_links(links)" in src # main() wired to the check
+ tree = ast.parse(src)
+ picked = [n for n in tree.body
+ if (isinstance(n, ast.FunctionDef) and n.name == "_bad_links")
+ or (isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") == "_SAFE_LINK")]
+ assert len(picked) == 2
+ ns: dict = {"re": _re}
+ exec(compile(ast.Module(body=picked, type_ignores=[]), str(rt_mod.WRAPPER), "exec"), ns)
+ bad = ns["_bad_links"](["body", "door_2", "DoorHandle", "../evil", "a/b", "Door.001", "", "9lives"])
+ assert bad == ["../evil", "a/b", "Door.001", "", "9lives"]