diff --git a/python/semantic_kernel/core_plugins/sessions_python_tool/sessions_python_plugin.py b/python/semantic_kernel/core_plugins/sessions_python_tool/sessions_python_plugin.py index 7d9ff5978b70..62184938e284 100644 --- a/python/semantic_kernel/core_plugins/sessions_python_tool/sessions_python_plugin.py +++ b/python/semantic_kernel/core_plugins/sessions_python_tool/sessions_python_plugin.py @@ -191,7 +191,10 @@ def _build_url_with_version(self, base_url, endpoint, params): return f"{base_url}{endpoint}?{query_string}" def _validate_local_path_for_upload(self, local_file_path: str) -> str: - """Validate local path is within allowed upload directories. + """Validate local path is within allowed upload directories and is not a directory. + + The path is canonicalized to ensure it resides inside an allowed directory. + Paths that resolve to an allowed directory itself or any subdirectory are rejected. Args: local_file_path: The path to validate. @@ -200,7 +203,8 @@ def _validate_local_path_for_upload(self, local_file_path: str) -> str: str: The canonicalized absolute path. Raises: - FunctionExecutionException: If file operations are disabled or path is not within allowed directories. + FunctionExecutionException: If file operations are disabled, path is not within allowed + directories, or path resolves to a directory. """ if not self.enable_dangerous_file_uploads: raise FunctionExecutionException( @@ -217,7 +221,11 @@ def _validate_local_path_for_upload(self, local_file_path: str) -> str: allowed_canonical = os.path.realpath(allowed_dir) try: common = os.path.commonpath([allowed_canonical, canonical_path]) - if common == allowed_canonical: + if ( + common == allowed_canonical + and canonical_path != allowed_canonical + and not os.path.isdir(canonical_path) + ): return canonical_path except ValueError: continue # Different drives on Windows diff --git a/python/tests/unit/core_plugins/test_sessions_python_plugin.py b/python/tests/unit/core_plugins/test_sessions_python_plugin.py index dc47b5a82a81..17d4e4e40504 100644 --- a/python/tests/unit/core_plugins/test_sessions_python_plugin.py +++ b/python/tests/unit/core_plugins/test_sessions_python_plugin.py @@ -885,6 +885,57 @@ async def test_upload_file_path_traversal_blocked(aca_python_sessions_unit_test_ await plugin.upload_file(local_file_path=traversal_path) +async def test_upload_file_denied_when_path_is_allowed_directory(aca_python_sessions_unit_test_env, tmp_path): + """Test that upload_file raises an exception when path is the allowed directory itself.""" + allowed_dir = tmp_path / "allowed" + allowed_dir.mkdir() + + plugin = SessionsPythonTool( + auth_callback=lambda: "sample_token", + enable_dangerous_file_uploads=True, + allowed_upload_directories={str(allowed_dir)}, + ) + + with pytest.raises(FunctionExecutionException, match="Access denied"): + await plugin.upload_file(local_file_path=str(allowed_dir)) + + +async def test_upload_file_denied_when_path_is_subdirectory(aca_python_sessions_unit_test_env, tmp_path): + """Test that upload_file raises an exception when path is a subdirectory inside allowed directory.""" + allowed_dir = tmp_path / "allowed" + allowed_dir.mkdir() + sub_dir = allowed_dir / "subdir" + sub_dir.mkdir() + + plugin = SessionsPythonTool( + auth_callback=lambda: "sample_token", + enable_dangerous_file_uploads=True, + allowed_upload_directories={str(allowed_dir)}, + ) + + with pytest.raises(FunctionExecutionException, match="Access denied"): + await plugin.upload_file(local_file_path=str(sub_dir)) + + +async def test_upload_file_denied_through_symlink_to_directory(aca_python_sessions_unit_test_env, tmp_path): + """Test that a symlink pointing to a directory is rejected in upload validation.""" + allowed_dir = tmp_path / "allowed" + allowed_dir.mkdir() + sub_dir = allowed_dir / "subdir" + sub_dir.mkdir() + link = allowed_dir / "link_to_dir" + _symlink_or_skip(link, sub_dir) + + plugin = SessionsPythonTool( + auth_callback=lambda: "sample_token", + enable_dangerous_file_uploads=True, + allowed_upload_directories={str(allowed_dir)}, + ) + + with pytest.raises(FunctionExecutionException, match="Access denied"): + await plugin.upload_file(local_file_path=str(link)) + + @patch("httpx.AsyncClient.get") @patch("httpx.AsyncClient.post") async def test_upload_file_succeeds_within_allowed_directory( @@ -944,6 +995,66 @@ async def async_return(result): mock_post.assert_awaited_once() +@patch("httpx.AsyncClient.get") +@patch("httpx.AsyncClient.post") +async def test_upload_file_nested_file_succeeds_within_allowed_directory( + mock_post, mock_get, aca_python_sessions_unit_test_env, tmp_path +): + """Test that upload_file succeeds for a file nested in a subdirectory within allowed directories.""" + + async def async_return(result): + return result + + allowed_dir = tmp_path / "allowed" + sub_dir = allowed_dir / "subdir" + sub_dir.mkdir(parents=True) + test_file = sub_dir / "nested_test.txt" + test_file.write_text("nested content") + + with patch( + "semantic_kernel.core_plugins.sessions_python_tool.sessions_python_plugin.SessionsPythonTool._ensure_auth_token", + return_value="test_token", + ): + mock_request = httpx.Request(method="POST", url="https://example.com/files/upload?identifier=None") + mock_response = httpx.Response( + status_code=200, + json={"$id": "1", "value": []}, + request=mock_request, + ) + mock_post.return_value = await async_return(mock_response) + + mock_get_request = httpx.Request(method="GET", url="https://example.com/files?identifier=None") + mock_get_response = httpx.Response( + status_code=200, + json={ + "$id": "1", + "value": [ + { + "$id": "2", + "properties": { + "$id": "3", + "filename": "nested_test.txt", + "size": 14, + "lastModifiedTime": "2024-07-02T19:29:23.4369699Z", + }, + }, + ], + }, + request=mock_get_request, + ) + mock_get.return_value = await async_return(mock_get_response) + + plugin = SessionsPythonTool( + auth_callback=lambda: "sample_token", + enable_dangerous_file_uploads=True, + allowed_upload_directories={str(allowed_dir)}, + ) + + result = await plugin.upload_file(local_file_path=str(test_file)) + assert result.filename == "nested_test.txt" + mock_post.assert_awaited_once() + + @patch("httpx.AsyncClient.get") async def test_download_file_works_without_allowed_directories(mock_get, aca_python_sessions_unit_test_env, tmp_path): """Test that download_file works without restrictions when allowed_download_directories is None."""