Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/uipath-platform/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Credentials can be provided via constructor parameters or environment variables

- **User authentication** — provide `base_url` and `secret` (access token), or set them via env vars
- **S2S (service-to-service)** — provide `client_id` with either `client_secret` or `client_assertion` (an OIDC token for federated credentials), optionally with `scope`; uses `ExternalApplicationService` internally to exchange for an access token
- **Token renewal** — a `UiPath()` whose secret came from the environment (`UiPathApiConfig.secret_from_environment`) re-reads `UNATTENDED_USER_ACCESS_TOKEN` / `UIPATH_ACCESS_TOKEN` on every request. An explicit `secret=` is sent as is.

Configuration is validated with Pydantic; missing `base_url` raises `BaseUrlMissingError`, missing `secret` raises `SecretMissingError`.

Expand Down
2 changes: 1 addition & 1 deletion packages/uipath-platform/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath-platform"
version = "0.3.12"
version = "0.3.13"
description = "HTTP client library for programmatic access to UiPath Platform"
readme = { file = "README.md", content-type = "text/markdown" }
requires-python = ">=3.11"
Expand Down
7 changes: 7 additions & 0 deletions packages/uipath-platform/src/uipath/platform/_uipath.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from functools import cached_property
from typing import Optional

Expand All @@ -18,6 +19,7 @@
)
from .common.auth import resolve_config_from_env
from .connections import ConnectionsService
from .constants import ENV_JOB_KEY
from .context_grounding import ContextGroundingService
from .documents import DocumentsService, DocumentsServiceV2
from .entities import EntitiesService
Expand Down Expand Up @@ -67,6 +69,8 @@ def __init__(
scope: Optional[str] = None,
debug: bool = False,
) -> None:
# A secret read from the environment is re-read on every request.
secret_from_environment = False
try:
if _has_valid_client_credentials(
client_id, client_secret, client_assertion
Expand All @@ -78,11 +82,14 @@ def __init__(
)
base_url, secret = service._base_url, token_data.access_token
else:
secret_from_environment = not secret
base_url, secret = resolve_config_from_env(base_url, secret)

self._config = UiPathApiConfig(
base_url=base_url,
secret=secret,
secret_from_environment=secret_from_environment,
environment_job_key=os.environ.get(ENV_JOB_KEY),
)
except ValidationError as e:
for error in e.errors():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ def request(
**kwargs: Any,
) -> Response:
if kwargs.get("include_folder_headers", False):
# httpx merges the client's default headers; do not copy them here.
kwargs["headers"] = {
**kwargs.get("headers", self._client.headers),
**kwargs.get("headers", {}),
**self.folder_headers,
}

Expand All @@ -48,8 +49,9 @@ async def request_async(
**kwargs: Any,
) -> Response:
if kwargs.get("include_folder_headers", False):
# httpx merges the client's default headers; do not copy them here.
kwargs["headers"] = {
**kwargs.get("headers", self._client_async.headers),
**kwargs.get("headers", {}),
**self.folder_headers,
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os
import sys
import types
from collections.abc import Mapping, MutableMapping
from logging import getLogger
from typing import Any, Literal, Union

Expand All @@ -21,7 +23,13 @@
stop_after_attempt,
)

from uipath.platform.constants import HEADER_TRACEPARENT_ID, HEADER_USER_AGENT
from uipath.platform.constants import (
ENV_JOB_KEY,
ENV_UIPATH_ACCESS_TOKEN,
ENV_UNATTENDED_USER_ACCESS_TOKEN,
HEADER_TRACEPARENT_ID,
HEADER_USER_AGENT,
)

from ..errors import EnrichedException
from ._config import UiPathApiConfig
Expand All @@ -41,6 +49,10 @@
_MAX_CALLER_FRAMES = 5


def _has_authorization_header(headers: Mapping[str, Any]) -> bool:
return any(str(name).lower() == "authorization" for name in headers)


def _get_caller_component() -> str:
try:
current: types.FrameType | None = sys._getframe(1)
Expand Down Expand Up @@ -204,9 +216,11 @@ def request(

specific_component = _get_caller_component()

kwargs.setdefault("headers", {})
# Copy: never write into the caller's dict.
kwargs["headers"] = dict(kwargs.get("headers") or {})
kwargs["headers"][HEADER_USER_AGENT] = user_agent_value(specific_component)
_inject_trace_context(kwargs["headers"])
self._add_authorization(kwargs["headers"])

override = resolve_service_url(str(url))
if override:
Expand Down Expand Up @@ -247,11 +261,13 @@ async def request_async(
f"HEADERS: {kwargs.get('headers', self._client_async.headers)}"
)

kwargs.setdefault("headers", {})
# Copy: never write into the caller's dict.
kwargs["headers"] = dict(kwargs.get("headers") or {})
kwargs["headers"][HEADER_USER_AGENT] = user_agent_value(
self._specific_component
)
_inject_trace_context(kwargs["headers"])
self._add_authorization(kwargs["headers"])

override = resolve_service_url(str(url))
if override:
Expand Down Expand Up @@ -279,9 +295,31 @@ def default_headers(self) -> dict[str, str]:

@property
def auth_headers(self) -> dict[str, str]:
header = f"Bearer {self._config.secret}"
header = f"Bearer {self._current_secret()}"
return {"Authorization": header}

def _current_secret(self) -> str:
"""The bearer token to send now; one from the environment is re-read."""
config = self._config
# Follow the environment only while it belongs to the job this config was built in.
same_job = os.environ.get(ENV_JOB_KEY) == config.environment_job_key
if config.secret_from_environment and same_job:
renewed = os.environ.get(
ENV_UNATTENDED_USER_ACCESS_TOKEN
) or os.environ.get(ENV_UIPATH_ACCESS_TOKEN)
if renewed:
self._config.secret = renewed
return renewed
return self._config.secret

def _add_authorization(self, headers: MutableMapping[str, Any]) -> None:
"""Send the environment's current token, unless the caller set a header."""
from_environment = self._config.secret_from_environment
if not from_environment or _has_authorization_header(headers):
return

headers["Authorization"] = f"Bearer {self._current_secret()}"

@property
def custom_headers(self) -> dict[str, str]:
return {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
class UiPathApiConfig(BaseModel):
base_url: str
secret: str
secret_from_environment: bool = False
environment_job_key: str | None = None


class ConfigurationManager:
Expand Down
Loading
Loading