"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(obs-studio): reject non-finite geometry in source transforms (#397)
Santhdea1ac8e577c
diff --git a/obs-studio/agent-harness/cli_anything/obs_studio/core/sources.py b/obs-studio/agent-harness/cli_anything/obs_studio/core/sources.pyindex 3e99c4a91..a3538ae76 100644--- a/obs-studio/agent-harness/cli_anything/obs_studio/core/sources.py+++ b/obs-studio/agent-harness/cli_anything/obs_studio/core/sources.py@@ -2,7 +2,16 @@import copyfrom typing import Dict, Any, List, Optional-from cli_anything.obs_studio.utils.obs_utils import generate_id, unique_name, get_item, validate_range+from cli_anything.obs_studio.utils.obs_utils import (+ generate_id,+ unique_name,+ get_item,+ validate_range,+ validate_position,+ validate_size,+ validate_crop,+ _finite_number,+)SOURCE_TYPES = {@@ -122,13 +131,9 @@ def add_source(src["visible"] = visibleif position:- src["position"] = {"x": float(position.get("x", 0)), "y": float(position.get("y", 0))}+ src["position"] = validate_position(position)if size:- w = int(size.get("width", 1920))- h = int(size.get("height", 1080))- if w < 1 or h < 1:- raise ValueError(f"Size must be positive: {w}x{h}")- src["size"] = {"width": w, "height": h}+ src["size"] = validate_size(size)if settings:src["settings"].update(settings)@@ -139,7 +144,7 @@ def add_source(def remove_source(project: Dict[str, Any], source_index: int, scene_index: int = 0) -> Dict[str, Any]:"""Remove a source from a scene."""sources = _get_scene_sources(project, scene_index)- source = get_item(sources, source_index, "source")+ get_item(sources, source_index, "source")return sources.pop(source_index)@@ -200,26 +205,43 @@ def transform_source(sources = _get_scene_sources(project, scene_index)source = get_item(sources, source_index, "source")+ new_pos = Noneif position:- source["position"] = {- "x": float(position.get("x", source["position"]["x"])),- "y": float(position.get("y", source["position"]["y"])),- }+ new_pos = validate_position(+ {+ "x": position.get("x", source["position"]["x"]),+ "y": position.get("y", source["position"]["y"]),+ }+ )++ new_size = Noneif size:- w = int(size.get("width", source["size"]["width"]))- h = int(size.get("height", source["size"]["height"]))- if w < 1 or h < 1:- raise ValueError(f"Size must be positive: {w}x{h}")- source["size"] = {"width": w, "height": h}+ new_size = validate_size(+ {+ "width": size.get("width", source["size"]["width"]),+ "height": size.get("height", source["size"]["height"]),+ }+ )++ new_crop = Noneif crop:- for key in ("top", "bottom", "left", "right"):- if key in crop:- val = int(crop[key])- if val < 0:- raise ValueError(f"Crop {key} must be non-negative, got {val}")- source["crop"][key] = val+ merged_crop = dict(source.get("crop") or {})+ merged_crop.update(crop)+ new_crop = validate_crop(merged_crop)++ new_rot = Noneif rotation is not None:- source["rotation"] = float(rotation)+ rot = _finite_number(rotation, "Rotation")+ new_rot = float(rot)++ if new_pos is not None:+ source["position"] = new_pos+ if new_size is not None:+ source["size"] = new_size+ if new_crop is not None:+ source["crop"] = new_crop+ if new_rot is not None:+ source["rotation"] = new_rotreturn sourcediff --git a/obs-studio/agent-harness/cli_anything/obs_studio/tests/test_validate_geometry_nan.py b/obs-studio/agent-harness/cli_anything/obs_studio/tests/test_validate_geometry_nan.pynew file mode 100644index 000000000..937ac9924--- /dev/null+++ b/obs-studio/agent-harness/cli_anything/obs_studio/tests/test_validate_geometry_nan.py@@ -0,0 +1,189 @@+"""Reject non-finite values in OBS geometry validators."""++from __future__ import annotations++import pytest+from decimal import Decimal+from fractions import Fraction+++from cli_anything.obs_studio.core.sources import add_source, transform_source+from cli_anything.obs_studio.utils.obs_utils import (+ validate_crop,+ validate_position,+ validate_size,+)+++def _project() -> dict:+ return {+ "scenes": [+ {+ "name": "Scene",+ "sources": [+ {+ "id": 0,+ "name": "Cam",+ "type": "browser",+ "visible": True,+ "locked": False,+ "opacity": 1.0,+ "rotation": 0.0,+ "position": {"x": 0.0, "y": 0.0},+ "size": {"width": 1920, "height": 1080},+ "crop": {"top": 0, "bottom": 0, "left": 0, "right": 0},+ "settings": {},+ }+ ],+ }+ ]+ }+++def test_validate_position_rejects_nan():+ with pytest.raises(ValueError, match="finite"):+ validate_position({"x": float("nan"), "y": 1.0})+++def test_validate_size_rejects_nan():+ with pytest.raises(ValueError, match="finite"):+ validate_size({"width": float("nan"), "height": 1080})+++def test_validate_crop_rejects_inf():+ with pytest.raises(ValueError, match="finite"):+ validate_crop({"left": float("inf"), "right": 0, "top": 0, "bottom": 0})+++def test_validate_position_accepts_finite():+ assert validate_position({"x": 1.5, "y": -2.0}) == {"x": 1.5, "y": -2.0}++def test_validate_position_preserves_large_int():+ assert validate_position({"x": 2 ** 53 + 1, "y": -(2 ** 53 + 3)}) == {+ "x": 2 ** 53 + 1,+ "y": -(2 ** 53 + 3),+ }+++def test_validate_size_preserves_large_int():+ assert validate_size(+ {"width": 2 ** 53 + 1, "height": 2 ** 53 + 3}+ ) == {"width": 2 ** 53 + 1, "height": 2 ** 53 + 3}++++ ("value", "expected"),+ [+ ("+42", 42),+ ("1", 1),+ (str(2 ** 53 + 1), 2 ** 53 + 1),+ ],+)+def test_validate_size_preserves_decimal_integer_strings(value, expected):+ """Keep signed, boundary, and large size strings exact before int conversion."""+ assert validate_size({"width": value, "height": value}) == {+ "width": expected,+ "height": expected,+ }++[email protected]("value", ["0", "-1"])+def test_validate_size_rejects_non_positive_decimal_integer_strings(value):+ """Reject size strings at and below the positive lower bound."""+ with pytest.raises(ValueError, match="positive"):+ validate_size({"width": value, "height": 1})++def test_validate_crop_preserves_large_int():+ assert validate_crop(+ {+ "top": 2 ** 53 + 1,+ "bottom": 2 ** 53 + 3,+ "left": 2 ** 53 + 5,+ "right": 2 ** 53 + 7,+ }+ ) == {+ "top": 2 ** 53 + 1,+ "bottom": 2 ** 53 + 3,+ "left": 2 ** 53 + 5,+ "right": 2 ** 53 + 7,+ }+++ ("value", "expected"),+ [+ ("+42", 42),+ ("0", 0),+ (str(2 ** 53 + 1), 2 ** 53 + 1),+ ],+)+def test_validate_crop_preserves_decimal_integer_strings(value, expected):+ """Keep signed, boundary, and large crop strings exact before int conversion."""+ assert validate_crop(+ {"top": value, "bottom": value, "left": value, "right": value}+ ) == {+ "top": expected,+ "bottom": expected,+ "left": expected,+ "right": expected,+ }+++def test_validate_crop_rejects_negative_decimal_integer_string():+ """Reject negative crop strings after exact integer parsing."""+ with pytest.raises(ValueError, match="non-negative"):+ validate_crop({"top": "-1"})+++def test_add_source_rejects_nan_position():+ with pytest.raises(ValueError, match="finite"):+ add_source(+ _project(),+ "browser",+ position={"x": float("nan"), "y": 0},+ )+++def test_transform_source_rejects_nan_position():+ with pytest.raises(ValueError, match="finite"):+ transform_source(_project(), 0, position={"x": float("nan")})+def test_validate_size_preserves_large_int_string():+ """Locks out regression where string integers were converted to float."""+ val = str(2 ** 53 + 1)+ assert validate_size({"width": val, "height": "1080"}) == {+ "width": 2 ** 53 + 1,+ "height": 1080,+ }+++def test_validate_size_preserves_decimal_and_fraction():+ """Locks out regression where Decimal and Fraction were converted to float."""+ dec = Decimal(2 ** 53 + 1)+ frac = Fraction(2 ** 53 + 3, 1)+ assert validate_size({"width": dec, "height": frac}) == {+ "width": 2 ** 53 + 1,+ "height": 2 ** 53 + 3,+ }+++def test_validate_size_rejects_float_strings():+ """Locks out regression where float strings '1.5' or '1e3' were truncated/accepted as size ints."""+ with pytest.raises(ValueError, match="integer"):+ validate_size({"width": "1.5", "height": 1080})+ with pytest.raises(ValueError, match="integer"):+ validate_size({"width": "1e3", "height": 1080})+++def test_transform_source_atomic_validation_on_invalid_rotation():+ """Locks out regression where earlier fields were mutated prior to rotation validation."""+ proj = _project()+ orig_pos = dict(proj["scenes"][0]["sources"][0]["position"])+ with pytest.raises(ValueError, match="finite"):+ transform_source(+ proj,+ 0,+ position={"x": 100.0, "y": 200.0},+ rotation=float("nan"),+ )+ assert proj["scenes"][0]["sources"][0]["position"] == orig_posdiff --git a/obs-studio/agent-harness/cli_anything/obs_studio/utils/obs_utils.py b/obs-studio/agent-harness/cli_anything/obs_studio/utils/obs_utils.pyindex cb445b8b7..a6e14fd33 100644--- a/obs-studio/agent-harness/cli_anything/obs_studio/utils/obs_utils.py+++ b/obs-studio/agent-harness/cli_anything/obs_studio/utils/obs_utils.py@@ -7,6 +7,65 @@ import copyfrom typing import Dict, Any, List, Optional++def _finite_number(value: Any, name: str) -> float | int:+ """Reject non-finite values without float-rounding large ints or integer strings."""+ if isinstance(value, bool):+ raise ValueError(f"{name} must be a finite number, got {value!r}")+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ if not math.isfinite(value):+ raise ValueError(f"{name} must be a finite number, got {value!r}")+ return value+ if isinstance(value, str):+ try:+ return int(value)+ except (TypeError, ValueError):+ pass+ try:+ num = float(value)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"{name} must be a finite number, got {value!r}") from exc+ if not math.isfinite(num):+ raise ValueError(f"{name} must be a finite number, got {value!r}")+ return num+ try:+ ival = int(value)+ if ival == value:+ return ival+ except Exception:+ pass+ try:+ num = float(value)+ except Exception as exc:+ raise ValueError(f"{name} must be a finite number, got {value!r}") from exc+ if not math.isfinite(num):+ raise ValueError(f"{name} must be a finite number, got {value!r}")+ return num+++def _finite_int(value: Any, name: str) -> int:+ """Reject non-finite or non-integer-form values without float rounding."""+ if isinstance(value, bool):+ raise ValueError(f"{name} must be a finite integer, got {value!r}")+ if isinstance(value, int):+ return value+ if isinstance(value, float):+ if not math.isfinite(value):+ raise ValueError(f"{name} must be a finite integer, got {value!r}")+ return int(value)+ if isinstance(value, str):+ try:+ return int(value)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"{name} must be a finite integer, got {value!r}") from exc+ try:+ val = int(value)+ except (TypeError, ValueError, ArithmeticError) as exc:+ raise ValueError(f"{name} must be a finite integer, got {value!r}") from exc+ return val+def generate_id(items: List[Dict[str, Any]]) -> int:"""Generate the next unique ID for a list of items."""if not items:@@ -37,16 +96,15 @@ def validate_range(value: float, min_val: float, max_val: float, name: str) -> fdef validate_position(pos: Dict[str, Any]) -> Dict[str, Any]:"""Validate and normalize a position dict."""- return {- "x": float(pos.get("x", 0)),- "y": float(pos.get("y", 0)),- }+ x = _finite_number(pos.get("x", 0), "Position x")+ y = _finite_number(pos.get("y", 0), "Position y")+ return {"x": x, "y": y}def validate_size(size: Dict[str, Any]) -> Dict[str, Any]:"""Validate and normalize a size dict."""- w = int(size.get("width", 1920))- h = int(size.get("height", 1080))+ w = _finite_int(size.get("width", 1920), "Size width")+ h = _finite_int(size.get("height", 1080), "Size height")if w < 1:raise ValueError(f"Width must be positive, got {w}")if h < 1:@@ -58,7 +116,7 @@ def validate_crop(crop: Dict[str, Any]) -> Dict[str, Any]:"""Validate and normalize a crop dict."""result = {}for key in ("top", "bottom", "left", "right"):- val = int(crop.get(key, 0))+ val = _finite_int(crop.get(key, 0), f"Crop {key}")if val < 0:raise ValueError(f"Crop {key} must be non-negative, got {val}")result[key] = val