Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(server): reject trailing newlines in label and resource-name validation
Jackmeson112a0de1fb52a
diff --git a/server/opensandbox_server/services/validators.py b/server/opensandbox_server/services/validators.pyindex 659ee5c76..9f949b48c 100644--- a/server/opensandbox_server/services/validators.py+++ b/server/opensandbox_server/services/validators.py@@ -76,11 +76,11 @@ def _is_valid_label_key(key: str) -> bool:# when the prefix uses its full 253-character allowance; this is valid.if len(prefix) > 253:return False- if not DNS_SUBDOMAIN_RE.match(prefix):+ if not DNS_SUBDOMAIN_RE.fullmatch(prefix):return Falseelse:name = key- if len(name) > 63 or not LABEL_NAME_RE.match(name):+ if len(name) > 63 or not LABEL_NAME_RE.fullmatch(name):return Falsereturn True@@ -88,7 +88,7 @@ def _is_valid_label_key(key: str) -> bool:def _is_valid_label_value(value: str) -> bool:if len(value) > 63:return False- return bool(LABEL_VALUE_RE.match(value))+ return bool(LABEL_VALUE_RE.fullmatch(value))def ensure_metadata_labels(metadata: Optional[Dict[str, str]]) -> None:@@ -291,7 +291,7 @@ def ensure_valid_volume_name(name: str) -> None:"message": f"Volume name '{name}' exceeds maximum length of 63 characters.",},)- if not VOLUME_NAME_RE.match(name):+ if not VOLUME_NAME_RE.fullmatch(name):raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail={@@ -459,7 +459,7 @@ def ensure_valid_pvc_name(claim_name: str) -> None:"message": f"PVC claim name '{claim_name}' exceeds maximum length of 253 characters.",},)- if not K8S_RESOURCE_NAME_RE.match(claim_name):+ if not K8S_RESOURCE_NAME_RE.fullmatch(claim_name):raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,detail={diff --git a/server/tests/test_routes_patch_metadata.py b/server/tests/test_routes_patch_metadata.pyindex f9f03639d..092af41f8 100644--- a/server/tests/test_routes_patch_metadata.py+++ b/server/tests/test_routes_patch_metadata.py@@ -20,6 +20,7 @@ from fastapi.testclient import TestClientfrom opensandbox_server.api import lifecyclefrom opensandbox_server.api.schema import ImageSpec, Sandbox, SandboxStatus+from opensandbox_server.services.sandbox_service import SandboxServicedef _make_sandbox(metadata: Optional[Dict[str, str]] = None) -> Sandbox:@@ -37,6 +38,30 @@ def _make_sandbox(metadata: Optional[Dict[str, str]] = None) -> Sandbox:class TestPatchMetadataRoute:+ def test_trailing_newline_rejected(self, client: TestClient, auth_headers: dict, monkeypatch) -> None:+ class StubService:+ @staticmethod+ def patch_sandbox_metadata(sandbox_id: str, patch: dict) -> Sandbox:+ metadata = SandboxService._apply_metadata_patch({}, patch)+ return _make_sandbox(metadata)++ monkeypatch.setattr(lifecycle, "sandbox_service", StubService())++ resp = client.patch(+ "/v1/sandboxes/sbx-001/metadata",+ json={"app": "web\n"},+ headers=auth_headers,+ )+ assert resp.status_code == 400+ assert resp.json() == {+ "code": "SANDBOX::INVALID_METADATA_LABEL",+ "message": (+ "Metadata value 'web\n' is invalid: must be 63 characters or less, "+ "start/end with an alphanumeric character, and contain only "+ "alphanumeric, '-', '_', or '.' characters."+ ),+ }+def test_add_keys(self, client: TestClient, auth_headers: dict, monkeypatch) -> None:sandbox = _make_sandbox({"team": "old"})diff --git a/server/tests/test_validators.py b/server/tests/test_validators.pyindex e7e30422a..dbe369594 100644--- a/server/tests/test_validators.py+++ b/server/tests/test_validators.py@@ -66,6 +66,38 @@ def test_ensure_metadata_labels_allows_none_or_empty():assert ensure_metadata_labels(None) is Noneassert ensure_metadata_labels({}) is None+[email protected]("whitespace", ["\n", "\r\n", "\r", "\t", " "])+ "key,value",+ [+ ("app{}", "web"),+ ("example.com/app{}", "web"),+ ("example.com{}/app", "web"),+ ("app", "web{}"),+ ("app", "{}"),+ ],+ ids=["name", "prefixed-name", "prefix", "value", "empty-value"],+)+def test_ensure_metadata_labels_rejects_whitespace(key, value, whitespace):+ with pytest.raises(HTTPException) as exc_info:+ ensure_metadata_labels({key.format(whitespace): value.format(whitespace)})+ assert exc_info.value.status_code == 400+ detail = exc_info.value.detail+ assert isinstance(detail, dict)+ assert detail.get("code") == SandboxErrorCodes.INVALID_METADATA_LABEL++[email protected]("value", ["we b", "web\nx"])+def test_ensure_metadata_labels_rejects_embedded_whitespace(value):+ with pytest.raises(HTTPException) as exc_info:+ ensure_metadata_labels({"app": value})+ assert exc_info.value.status_code == 400+ detail = exc_info.value.detail+ assert isinstance(detail, dict)+ assert detail.get("code") == SandboxErrorCodes.INVALID_METADATA_LABEL++def test_ensure_metadata_labels_rejects_name_too_long():long_name = "a" * 64with pytest.raises(HTTPException) as exc_info:@@ -207,6 +239,15 @@ class TestEnsureValidVolumeName:assert exc_info.value.status_code == 400assert exc_info.value.detail["code"] == SandboxErrorCodes.INVALID_VOLUME_NAME+ @pytest.mark.parametrize("whitespace", ["\n", "\r\n", "\r", "\t", " "])+ def test_name_with_trailing_whitespace_raises(self, whitespace):+ with pytest.raises(HTTPException) as exc_info:+ ensure_valid_volume_name("data" + whitespace)+ assert exc_info.value.status_code == 400+ detail = exc_info.value.detail+ assert isinstance(detail, dict)+ assert detail.get("code") == SandboxErrorCodes.INVALID_VOLUME_NAME+class TestEnsureValidMountPath:def test_valid_absolute_path(self):@@ -351,6 +392,15 @@ class TestEnsureValidPvcName:assert exc_info.value.status_code == 400assert exc_info.value.detail["code"] == SandboxErrorCodes.INVALID_PVC_NAME+ @pytest.mark.parametrize("whitespace", ["\n", "\r\n", "\r", "\t", " "])+ def test_name_with_trailing_whitespace_raises(self, whitespace):+ with pytest.raises(HTTPException) as exc_info:+ ensure_valid_pvc_name("my-pvc" + whitespace)+ assert exc_info.value.status_code == 400+ detail = exc_info.value.detail+ assert isinstance(detail, dict)+ assert detail.get("code") == SandboxErrorCodes.INVALID_PVC_NAME+class TestEnsureVolumesValid:def test_none_volumes_valid(self):