scene actions: device-name spellings, missing glTF references, link message kept, no folders on refused render

- check_relative: spaces before the first dot are dropped (CON .txt), superscript COM/LPT digits are device names.
- gltf_references refuses a reference to a missing file; drops the broad ValueError catch and redundant relative_to so the specific refusal (a link) reaches the receipt.
- _render_still makes folders only after every Blender-side refusal (unknown engine used to leave them behind).
- Tests for each.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-07 15:10:58 +00:00
commit dbd4cc05d1
3 changed files with 60 additions and 24 deletions

View file

@ -598,8 +598,8 @@ class BrokkrBlenderTarget:
path = sa.resolve_inside(self.import_dir, name, "import")
sa.require_gltf(path)
stamped = sa.fingerprint([path]) # before the parse, so a swap during it shows
references = sa.gltf_references(path, self.import_dir)
existing = [r for r in references if r.exists()]
references = sa.gltf_references(path)
existing = references # gltf_references refuses a missing one
checked = (stamped, sa.fingerprint(existing))
# Re-check immediately before use: the same path, the same files, the same bytes' stats.
# Blender then opens the files itself, so a swap in that last gap is not prevented
@ -711,13 +711,6 @@ class BrokkrBlenderTarget:
# Render settings are the intent's for this render only; put them back afterwards.
saved = (render.engine, render.resolution_x, render.resolution_y, render.filepath,
render.image_settings.file_format, scene.camera)
path.parent.mkdir(parents=True, exist_ok=True)
# Re-check after the folders exist and immediately before use: no link was swapped in,
# and the name is still free. Blender opens the file itself afterwards, so a swap in
# that last gap is not prevented (residual TOCTOU): the output directory must only
# be writable by trusted users.
if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path:
raise sa.ActionRefused("Output path changed while it was being checked.")
try:
if engine is not None:
try:
@ -732,6 +725,14 @@ class BrokkrBlenderTarget:
scene.camera = camera
render.filepath = str(path)
render.image_settings.file_format = file_format
# Folders are made only after every refusal that can still come from Blender (an unknown
# engine), so a refused render leaves none behind. Then re-check after the folders exist
# and immediately before use: no link was swapped in, and the name is still free. Blender
# opens the file itself afterwards, so a swap in that last gap is not prevented (residual
# TOCTOU): the output directory must only be writable by trusted users.
path.parent.mkdir(parents=True, exist_ok=True)
if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path:
raise sa.ActionRefused("Output path changed while it was being checked.")
self.bpy.ops.render.render(write_still=True)
finally:
(render.engine, render.resolution_x, render.resolution_y, render.filepath,

View file

@ -28,7 +28,7 @@ class ActionRefused(ValueError):
WINDOWS_DEVICE_NAMES = frozenset(
["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
+ [f"COM{i}" for i in range(1, 10)] + [f"LPT{i}" for i in range(1, 10)]
+ [f"COM{i}" for i in "123456789\u00b9\u00b2\u00b3"] + [f"LPT{i}" for i in "123456789\u00b9\u00b2\u00b3"]
)
MAX_GLTF_JSON_BYTES = 16 * 1024 * 1024
@ -58,7 +58,8 @@ def check_relative(candidate: str, label: str) -> list[str]:
raise ActionRefused(f"{label} path may not contain '..'.")
if part[-1] in ". ":
raise ActionRefused(f"{label} path component {part!r} ends in a dot or space.")
if part.split(".")[0].upper() in WINDOWS_DEVICE_NAMES:
# Windows reads "CON .txt" as CON: trailing spaces before the first dot do not count.
if part.split(".")[0].rstrip(" ").upper() in WINDOWS_DEVICE_NAMES:
raise ActionRefused(f"{label} path component {part!r} is a Windows device name.")
return parts
@ -110,14 +111,14 @@ def fingerprint(paths: Iterable[Path]) -> tuple:
return tuple(out)
def gltf_references(path: Path, root: str) -> list[Path]:
"""Every external file a .gltf or .glb names, checked to lie under root; [] for self-contained.
def gltf_references(path: Path) -> list[Path]:
"""Every external file a .gltf or .glb names, checked to exist inside path's folder; [] for self-contained.
Parses the glTF JSON (the .gltf file, or a .glb's first chunk) and takes every
buffers[].uri and images[].uri. A data: URI is inline and fine. Anything else is
percent-decoded and must pass check_relative (so file:, http:, drive, UNC, rooted and
.. forms are refused), then resolve under the .gltf's own folder and stay under root
with no link on the way."""
.. forms are refused), then resolve under the .gltf's own folder (itself already checked under the import root)
with no link on the way, and must exist."""
raw = path.read_bytes() if path.suffix.lower() == ".gltf" else _glb_json_chunk(path)
if len(raw) > MAX_GLTF_JSON_BYTES:
raise ActionRefused("glTF JSON is too large to check.")
@ -129,7 +130,6 @@ def gltf_references(path: Path, root: str) -> list[Path]:
raise ActionRefused("Import file is not a glTF object.")
references: list[Path] = []
here = path.parent.resolve()
base = Path(root).resolve()
for kind in ("buffers", "images"):
entries = document.get(kind, [])
if not isinstance(entries, list):
@ -144,11 +144,10 @@ def gltf_references(path: Path, root: str) -> list[Path]:
continue
decoded = unquote(uri)
relative = "/".join(check_relative(decoded, f"glTF {kind} uri"))
try:
target = resolve_inside(str(here), relative, f"glTF {kind} uri")
target.resolve().relative_to(base)
except ValueError:
raise ActionRefused(f"glTF {kind} uri is outside the import directory.") from None
# path is already under root, so here is too, and resolve_inside keeps the reference under here.
target = resolve_inside(str(here), relative, f"glTF {kind} uri")
if not target.exists():
raise ActionRefused(f"glTF {kind} uri names a file that does not exist: {relative}")
references.append(target)
return references

View file

@ -298,7 +298,23 @@ class ActionTests(unittest.TestCase):
except OSError:
self.skipTest("symlinks unavailable")
self.write_gltf("link.gltf", {"asset": {"version": "2.0"}, "buffers": [{"uri": "buf.bin"}]})
self.assertEqual(self.run_action(action="importGltf", filepath="link.gltf")["status"], "failed")
receipt = self.run_action(action="importGltf", filepath="link.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertIn("link", receipt["message"]) # the rule that fired, not a generic "outside"
self.assertEqual(self.bpy.imported, [])
def test_gltf_reference_to_a_missing_file_is_refused(self):
try:
os.symlink(self.root / "nowhere.bin", self.root / "in" / "dangling.bin")
dangling = True
except OSError:
dangling = False
for kind in ("buffers", "images"):
for uri in ["absent.bin", "sub/absent.png"] + (["dangling.bin"] if dangling else []):
self.write_gltf("miss.gltf", {"asset": {"version": "2.0"}, kind: [{"uri": uri}]})
receipt = self.run_action(action="importGltf", filepath="miss.gltf")
self.assertEqual(receipt["status"], "failed", (kind, uri))
self.assertRegex(receipt["message"], "does not exist|link", (kind, uri))
self.assertEqual(self.bpy.imported, [])
def test_malformed_gltf_is_refused(self):
@ -315,8 +331,8 @@ class ActionTests(unittest.TestCase):
target_file = self.root / "in" / "model.glb"
original = sa.gltf_references
def swap_after_check(path, root):
result = original(path, root)
def swap_after_check(path):
result = original(path)
target_file.write_bytes(glb_bytes({"asset": {"version": "2.0"}, "extras": "x" * 50}))
return result
with mock.patch.object(sa, "gltf_references", swap_after_check):
@ -353,6 +369,17 @@ class ActionTests(unittest.TestCase):
self.assertEqual(self.bpy.rendered, [])
self.assertEqual(list(outside.iterdir()), [])
def test_a_refused_render_leaves_no_folders_behind(self):
(self.root / "out" / "taken").mkdir()
(self.root / "out" / "taken" / "a.png").write_bytes(b"x")
for case in ({"outputPath": "new/deep/a.png", "resolutionX": 0}, {"outputPath": "new/deep/a.png", "engine": ""}, {"outputPath": "new/deep/a.png", "engine": "NOPE"},
{"outputPath": "new/deep/a.png", "cameraName": "Nope"}, {"outputPath": "new/deep/a.txt"},
{"outputPath": "taken/a.png"}):
self.assertEqual(self.run_action(action="renderStill", **case)["status"], "failed", case)
self.assertIn("already exists", self.run_action(action="renderStill", outputPath="taken/a.png")["message"])
self.assertEqual(sorted(p.name for p in (self.root / "out").iterdir()), ["taken"])
self.assertEqual(self.bpy.rendered, [])
def test_render_refuses_drive_unc_extended_stream_and_device_names(self):
for name in ("C:a.png", "C:\\a.png", "\\\\host\\share\\a.png", "\\\\?\\C:\\a.png", "a.png:stream",
"/a.png", "NUL.png", "a.png.", "x/../a.png"):
@ -391,6 +418,15 @@ class PathTests(unittest.TestCase):
with self.assertRaises(sa.ActionRefused, msg=name):
sa.resolve_inside(tmp, name, "output")
def test_check_relative_refuses_device_names_however_windows_spells_them(self):
# Windows drops spaces before the first dot (CON .txt is CON) and reads superscript digits as COM/LPT digits.
for name in ("CON", "con", "CON .txt", "NUL .png", "sub/NUL .png", "COM1", "COM\u00b9", "LPT\u00b2.txt", "LPT\u00b3",
"CONIN$", "a/PRN.tar.gz"):
with self.assertRaisesRegex(sa.ActionRefused, "device", msg=name):
sa.check_relative(name, "output")
for name in ("CONSOLE.png", "COM10.png", "com.png", "a.CON.png", "NULL"):
sa.check_relative(name, "output")
def test_check_relative_itself_refuses_dotdot_and_nul(self):
# Each rule on its own: resolve_inside's link walk also trips on '..', so only a
# direct call proves the text rule.