diff --git a/packages/uipath-platform/pyproject.toml b/packages/uipath-platform/pyproject.toml index cb22f5c61..9b7e59701 100644 --- a/packages/uipath-platform/pyproject.toml +++ b/packages/uipath-platform/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" description = "HTTP client library for programmatic access to UiPath Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath-platform/src/uipath/platform/connections/_connections_service.py b/packages/uipath-platform/src/uipath/platform/connections/_connections_service.py index 7172a6f4a..e89114280 100644 --- a/packages/uipath-platform/src/uipath/platform/connections/_connections_service.py +++ b/packages/uipath-platform/src/uipath/platform/connections/_connections_service.py @@ -15,10 +15,14 @@ from ..orchestrator._folder_service import FolderService from ._execution_service import ( _ORIGINATOR_VALUE, + EXECUTABLE_HEADERS, HEADER_ACTIVITY_JOB_ID, + HEADER_IS_EXECUTABLE_ID, + HEADER_IS_EXECUTABLE_TYPE, HEADER_ORIGINATOR, HEADER_SOURCE, ConnectionExecutionMixin, + executable_headers, ) from .connections import ( ActivityMetadata, @@ -33,6 +37,8 @@ __all__ = [ "HEADER_ACTIVITY_JOB_ID", + "HEADER_IS_EXECUTABLE_ID", + "HEADER_IS_EXECUTABLE_TYPE", "HEADER_ORIGINATOR", "HEADER_SOURCE", "ConnectionsService", @@ -779,7 +785,9 @@ def _build_activity_request_spec( elif param_name in activity_metadata.parameter_location_info.path_params: path_params[param_name] = value_str elif param_name in activity_metadata.parameter_location_info.header_params: - header_params[param_name] = value_str + # Only the job's environment sets the executable headers, never an input. + if param_name.lower() not in EXECUTABLE_HEADERS: + header_params[param_name] = value_str elif ( param_name in activity_metadata.parameter_location_info.multipart_params ): @@ -800,6 +808,7 @@ def _build_activity_request_spec( } if job_key := UiPathConfig.job_key: headers[HEADER_ACTIVITY_JOB_ID] = job_key + headers.update(executable_headers()) # body and files handling json_data: Dict[str, Any] | None = None diff --git a/packages/uipath-platform/src/uipath/platform/connections/_execution_service.py b/packages/uipath-platform/src/uipath/platform/connections/_execution_service.py index 35b51c162..92ba04574 100644 --- a/packages/uipath-platform/src/uipath/platform/connections/_execution_service.py +++ b/packages/uipath-platform/src/uipath/platform/connections/_execution_service.py @@ -1,6 +1,7 @@ """Running a connector activity or a vendor HTTP request through a connection.""" import time +import uuid from collections.abc import Sequence from typing import Any from urllib.parse import urlsplit @@ -11,12 +12,13 @@ from ..common._base_service import BaseService, _inject_trace_context from ..common._bindings import resource_override -from ..common._config import UiPathConfig +from ..common._config import UiPathConfig, resolve_execution_type from ..common._folder_context import header_folder from ..common._service_url_overrides import ( inject_routing_headers, resolve_service_url, ) +from ..common._span_utils import ExecutionType from ..common._user_agent import user_agent_value from ..common.retry import ( RETRYABLE_STATUS_CODES, @@ -39,6 +41,36 @@ HEADER_ACTIVITY_JOB_ID = "x-uipath-job-id" _ORIGINATOR_VALUE = "uipath-python" +# The automation that makes an Integration Service call. Integration Service applies +# its access policies to this automation (an Agent and its process key). +HEADER_IS_EXECUTABLE_TYPE = "x-uipath-is-executable-type" +HEADER_IS_EXECUTABLE_ID = "x-uipath-is-executable-id" +EXECUTABLE_HEADERS = frozenset({HEADER_IS_EXECUTABLE_TYPE, HEADER_IS_EXECUTABLE_ID}) +_EXECUTABLE_TYPE_AGENT = "Agent" + + +def executable_headers() -> dict[str, str]: + """The executable headers of an Integration Service call from a deployed job. + + The SDK sends both headers or neither. It sends them only for a deployed + Orchestrator job: the run has a job key, it is not a debug run, and its + process key is a GUID. The values come from the job's environment, never + from the caller's input. A local run or a debug run sends no headers, as + Maestro and agents-api do. + """ + if not UiPathConfig.job_key or resolve_execution_type() != ExecutionType.RUNTIME: + return {} + try: + process_key = uuid.UUID((UiPathConfig.process_uuid or "").strip()) + except ValueError: + return {} + return { + HEADER_IS_EXECUTABLE_TYPE: _EXECUTABLE_TYPE_AGENT, + # The canonical form: Integration Service reads only a hyphenated GUID. + HEADER_IS_EXECUTABLE_ID: str(process_key), + } + + # Statuses of the Integration Service call that an opted-in retry sends again. _EXECUTE_RETRYABLE_STATUS_CODES = RETRYABLE_STATUS_CODES | {500} _EXECUTE_INITIAL_BACKOFF = 0.5 @@ -723,6 +755,7 @@ def _execute_call( } if job_key := UiPathConfig.job_key: headers[HEADER_ACTIVITY_JOB_ID] = job_key + headers.update(executable_headers()) _inject_trace_context(headers) # The token of the moment: a renewed one replaces the client's own self._add_authorization(headers) diff --git a/packages/uipath-platform/tests/services/test_connections_execution.py b/packages/uipath-platform/tests/services/test_connections_execution.py index a78e6baf6..1905777cc 100644 --- a/packages/uipath-platform/tests/services/test_connections_execution.py +++ b/packages/uipath-platform/tests/services/test_connections_execution.py @@ -12,6 +12,7 @@ from pytest_httpx import HTTPXMock from uipath.platform import UiPathApiConfig, UiPathExecutionContext +from uipath.platform.common import UiPathConfig from uipath.platform.common._bindings import ( ConnectionResourceOverwrite, _resource_overwrites, @@ -1527,3 +1528,94 @@ def test_object_name_dots_inside_a_segment_are_allowed( httpx_mock.add_response(url=f"{instance_url}/files/report..v1.pdf", json={}) assert service.execute_activity(CONNECTION_ID, "files/report..v1.pdf").ok + + +class TestExecutableHeaders: + """The access policy headers on an execute call: the automation that makes the call.""" + + PROCESS_KEY = "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" + + @pytest.fixture(autouse=True) + def _deployed_job(self, monkeypatch: pytest.MonkeyPatch, tmp_path) -> Any: + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("UIPATH_JOB_KEY", "job-key-abc") + monkeypatch.setenv("UIPATH_PROCESS_UUID", self.PROCESS_KEY) + monkeypatch.delenv("UIPATH_IS_DEBUG", raising=False) + UiPathConfig.reset() + yield + UiPathConfig.reset() + + def test_execute_activity_in_a_job( + self, httpx_mock: HTTPXMock, service: ConnectionsService, instance_url: str + ) -> None: + httpx_mock.add_response(url=f"{instance_url}/tickets", json=[]) + + service.execute_activity(CONNECTION_ID, "tickets") + + request = sent(httpx_mock) + assert request.headers["x-uipath-is-executable-type"] == "Agent" + assert request.headers["x-uipath-is-executable-id"] == self.PROCESS_KEY + + def test_execute_http_in_a_job_keeps_vendor_headers_in_the_body( + self, httpx_mock: HTTPXMock, service: ConnectionsService, instance_url: str + ) -> None: + httpx_mock.add_response( + url=f"{instance_url}/http-request", + json={"code": 200, "statusText": "OK", "headers": {}, "body": {}}, + ) + + service.execute_http( + CONNECTION_ID, + "/v2/tickets", + "GET", + headers={"x-uipath-is-executable-type": "AgenticProcess"}, + ) + + request = sent(httpx_mock) + assert request.headers["x-uipath-is-executable-type"] == "Agent" + assert request.headers["x-uipath-is-executable-id"] == self.PROCESS_KEY + # A vendor header goes to the vendor in the proxy body, not to Integration Service. + assert json.loads(request.content)["headers"] == { + "x-uipath-is-executable-type": "AgenticProcess" + } + + async def test_execute_activity_async_in_a_job( + self, httpx_mock: HTTPXMock, service: ConnectionsService, instance_url: str + ) -> None: + httpx_mock.add_response(url=f"{instance_url}/tickets", json=[]) + + await service.execute_activity_async(CONNECTION_ID, "tickets") + + request = sent(httpx_mock) + assert request.headers["x-uipath-is-executable-id"] == self.PROCESS_KEY + + def test_debug_run_sends_no_headers( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + instance_url: str, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv("UIPATH_IS_DEBUG", "true") + httpx_mock.add_response(url=f"{instance_url}/tickets", json=[]) + + service.execute_activity(CONNECTION_ID, "tickets") + + request = sent(httpx_mock) + assert "x-uipath-is-executable-type" not in request.headers + assert "x-uipath-is-executable-id" not in request.headers + + def test_local_run_sends_no_headers( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + instance_url: str, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.delenv("UIPATH_JOB_KEY", raising=False) + httpx_mock.add_response(url=f"{instance_url}/tickets", json=[]) + + service.execute_activity(CONNECTION_ID, "tickets") + + request = sent(httpx_mock) + assert "x-uipath-is-executable-type" not in request.headers diff --git a/packages/uipath-platform/tests/services/test_connections_service.py b/packages/uipath-platform/tests/services/test_connections_service.py index c9fa45441..21100e01d 100644 --- a/packages/uipath-platform/tests/services/test_connections_service.py +++ b/packages/uipath-platform/tests/services/test_connections_service.py @@ -1,13 +1,16 @@ import json +from collections.abc import Iterator +from typing import Any from unittest.mock import AsyncMock, MagicMock from urllib.parse import unquote_plus +import httpx import pytest from pydantic import ValidationError from pytest_httpx import HTTPXMock from uipath.platform import UiPathApiConfig, UiPathExecutionContext -from uipath.platform.common import jsonschema_to_pydantic +from uipath.platform.common import UiPathConfig, jsonschema_to_pydantic from uipath.platform.connections import ( ActivityMetadata, ActivityParameterLocationInfo, @@ -18,6 +21,8 @@ ) from uipath.platform.connections._connections_service import ( HEADER_ACTIVITY_JOB_ID, + HEADER_IS_EXECUTABLE_ID, + HEADER_IS_EXECUTABLE_TYPE, ConnectionsService, ) from uipath.platform.constants import HEADER_FOLDER_KEY, HEADER_USER_AGENT @@ -2438,3 +2443,190 @@ def test_invoke_activity_multipart_bool_scalar_is_lowercase( flag_part = _multipart_part(sent_request.content, boundary, "flag") assert flag_part.rstrip().endswith("true") + + +PROCESS_KEY = "6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b" + + +@pytest.fixture +def deployed_job(monkeypatch: pytest.MonkeyPatch, tmp_path) -> Iterator[None]: + """A deployed Orchestrator job: a job key, a process key and no debug signal.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("UIPATH_JOB_KEY", "job-key-abc") + monkeypatch.setenv("UIPATH_PROCESS_UUID", PROCESS_KEY) + monkeypatch.delenv("UIPATH_IS_DEBUG", raising=False) + UiPathConfig.reset() + yield + UiPathConfig.reset() + + +class TestExecutableHeaders: + """The access policy headers on an activity call: the automation that makes the call.""" + + @staticmethod + def _invoke( + httpx_mock: HTTPXMock, + service: ConnectionsService, + metadata: ActivityMetadata, + activity_input: dict[str, Any], + ) -> httpx.Request: + connection_id = "test-connection-123" + httpx_mock.add_response( + method="GET", + status_code=200, + json={"id": connection_id, "name": "Test", "elementInstanceId": 1}, + ) + httpx_mock.add_response(method="POST", status_code=200, json={}) + service.invoke_activity( + activity_metadata=metadata, + connection_id=connection_id, + activity_input=activity_input, + ) + return httpx_mock.get_requests()[1] + + def test_deployed_job_sends_agent_and_process_key( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + simple_activity_metadata: ActivityMetadata, + deployed_job: None, + ) -> None: + sent = self._invoke( + httpx_mock, service, simple_activity_metadata, {"body_field1": "x"} + ) + + assert sent.headers[HEADER_IS_EXECUTABLE_TYPE] == "Agent" + assert sent.headers[HEADER_IS_EXECUTABLE_ID] == PROCESS_KEY + + async def test_async_invoke_sends_the_same_headers( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + simple_activity_metadata: ActivityMetadata, + deployed_job: None, + ) -> None: + connection_id = "test-connection-123" + httpx_mock.add_response( + method="GET", + status_code=200, + json={"id": connection_id, "name": "Test", "elementInstanceId": 1}, + ) + httpx_mock.add_response(method="POST", status_code=200, json={}) + + await service.invoke_activity_async( + activity_metadata=simple_activity_metadata, + connection_id=connection_id, + activity_input={"body_field1": "x"}, + ) + + sent = httpx_mock.get_requests()[1] + assert sent.headers[HEADER_IS_EXECUTABLE_TYPE] == "Agent" + assert sent.headers[HEADER_IS_EXECUTABLE_ID] == PROCESS_KEY + + def test_process_key_is_sent_in_canonical_form( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + simple_activity_metadata: ActivityMetadata, + deployed_job: None, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setenv("UIPATH_PROCESS_UUID", "{" + PROCESS_KEY.upper() + "}") + + sent = self._invoke( + httpx_mock, service, simple_activity_metadata, {"body_field1": "x"} + ) + + assert sent.headers[HEADER_IS_EXECUTABLE_ID] == PROCESS_KEY + + @pytest.mark.parametrize( + ("env", "value"), + [ + ("UIPATH_JOB_KEY", None), + ("UIPATH_PROCESS_UUID", None), + ("UIPATH_PROCESS_UUID", "not-a-guid"), + ("UIPATH_IS_DEBUG", "true"), + ], + ids=["local-run", "no-process-key", "bad-process-key", "debug-run"], + ) + def test_no_headers_outside_a_deployed_job( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + simple_activity_metadata: ActivityMetadata, + deployed_job: None, + monkeypatch: pytest.MonkeyPatch, + env: str, + value: str | None, + ) -> None: + if value is None: + monkeypatch.delenv(env, raising=False) + else: + monkeypatch.setenv(env, value) + + sent = self._invoke( + httpx_mock, service, simple_activity_metadata, {"body_field1": "x"} + ) + + assert HEADER_IS_EXECUTABLE_TYPE not in sent.headers + assert HEADER_IS_EXECUTABLE_ID not in sent.headers + + def test_orchestrator_debug_job_sends_no_headers( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + simple_activity_metadata: ActivityMetadata, + deployed_job: None, + tmp_path, + ) -> None: + # A Maestro solution debug runs a deployed process under a debug job. + (tmp_path / "uipath.json").write_text( + '{"runtime": {"internalArguments": {"isDebug": true}}}' + ) + UiPathConfig.reset() + + sent = self._invoke( + httpx_mock, service, simple_activity_metadata, {"body_field1": "x"} + ) + + assert HEADER_IS_EXECUTABLE_TYPE not in sent.headers + + @pytest.mark.parametrize( + "name", ["x-uipath-is-executable-type", "X-UiPath-Is-Executable-Id"] + ) + @pytest.mark.parametrize("in_job", [True, False], ids=["job", "local-run"]) + def test_activity_input_cannot_set_the_headers( + self, + httpx_mock: HTTPXMock, + service: ConnectionsService, + deployed_job: None, + monkeypatch: pytest.MonkeyPatch, + name: str, + in_job: bool, + ) -> None: + if not in_job: + monkeypatch.delenv("UIPATH_JOB_KEY", raising=False) + metadata = ActivityMetadata( + object_path="/elements/test-connector/test-activity", + method_name="POST", + content_type="application/json", + parameter_location_info=ActivityParameterLocationInfo( + header_params=[name, "custom_header"], + body_fields=["body_field1"], + ), + ) + + sent = self._invoke( + httpx_mock, + service, + metadata, + {name: "AgenticProcess", "custom_header": "kept", "body_field1": "x"}, + ) + + assert sent.headers["custom_header"] == "kept" + values = [v for k, v in sent.headers.multi_items() if k.lower() == name.lower()] + if in_job: + expected = "Agent" if name.lower().endswith("type") else PROCESS_KEY + assert values == [expected] + else: + assert values == [] diff --git a/packages/uipath-platform/uv.lock b/packages/uipath-platform/uv.lock index 6e32115d0..696e14dcb 100644 --- a/packages/uipath-platform/uv.lock +++ b/packages/uipath-platform/uv.lock @@ -1091,7 +1091,7 @@ dev = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "." } dependencies = [ { name = "anyio" }, diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ee06f3d06..31a266eb8 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2883,7 +2883,7 @@ wheels = [ [[package]] name = "uipath-platform" -version = "0.3.23" +version = "0.3.24" source = { editable = "../uipath-platform" } dependencies = [ { name = "anyio" },