-
Notifications
You must be signed in to change notification settings - Fork 23
feat: add client credentials unattended auth flow #404
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| from typing import Optional | ||
| from urllib.parse import urlparse | ||
|
|
||
| import httpx | ||
|
|
||
| from .._utils._console import ConsoleLogger | ||
| from ._models import TokenData | ||
| from ._utils import parse_access_token, update_env_file | ||
|
|
||
| console = ConsoleLogger() | ||
|
|
||
|
|
||
| class ClientCredentialsService: | ||
| """Service for client credentials authentication flow.""" | ||
|
|
||
| def __init__(self, domain: str): | ||
| self.domain = domain | ||
|
|
||
| def get_token_url(self) -> str: | ||
| """Get the token URL for the specified domain.""" | ||
| match self.domain: | ||
| case "alpha": | ||
| return "https://alpha.uipath.com/identity_/connect/token" | ||
| case "staging": | ||
| return "https://staging.uipath.com/identity_/connect/token" | ||
| case _: # cloud (default) | ||
| return "https://cloud.uipath.com/identity_/connect/token" | ||
|
|
||
| def _is_valid_domain_or_subdomain(self, hostname: str, domain: str) -> bool: | ||
| """Check if hostname is either an exact match or a valid subdomain of the domain. | ||
|
|
||
| Args: | ||
| hostname: The hostname to check | ||
| domain: The domain to validate against | ||
|
|
||
| Returns: | ||
| True if hostname is valid domain or subdomain, False otherwise | ||
| """ | ||
| return hostname == domain or hostname.endswith(f".{domain}") | ||
|
|
||
| def extract_domain_from_base_url(self, base_url: str) -> str: | ||
| """Extract domain from base URL. | ||
|
|
||
| Args: | ||
| base_url: The base URL to extract domain from | ||
|
|
||
| Returns: | ||
| The domain (alpha, staging, or cloud) | ||
| """ | ||
| try: | ||
| parsed = urlparse(base_url) | ||
| hostname = parsed.hostname | ||
|
|
||
| if hostname: | ||
| match hostname: | ||
| case h if self._is_valid_domain_or_subdomain(h, "alpha.uipath.com"): | ||
| return "alpha" | ||
| case h if self._is_valid_domain_or_subdomain( | ||
| h, "staging.uipath.com" | ||
| ): | ||
| return "staging" | ||
| case h if self._is_valid_domain_or_subdomain(h, "cloud.uipath.com"): | ||
| return "cloud" | ||
|
|
||
| # Default to cloud if we can't determine | ||
| return "cloud" | ||
| except Exception: | ||
| # Default to cloud if parsing fails | ||
| return "cloud" | ||
|
|
||
| def authenticate( | ||
| self, client_id: str, client_secret: str, scope: str = "OR.Execution" | ||
| ) -> Optional[TokenData]: | ||
| """Authenticate using client credentials flow. | ||
|
|
||
| Args: | ||
| client_id: The client ID for authentication | ||
| client_secret: The client secret for authentication | ||
| scope: The scope for the token (default: OR.Execution) | ||
|
|
||
| Returns: | ||
| Token data if successful, None otherwise | ||
| """ | ||
| token_url = self.get_token_url() | ||
|
|
||
| data = { | ||
| "grant_type": "client_credentials", | ||
| "client_id": client_id, | ||
| "client_secret": client_secret, | ||
| "scope": scope, | ||
| } | ||
|
|
||
| try: | ||
| with httpx.Client(timeout=30.0) as client: | ||
| response = client.post(token_url, data=data) | ||
|
|
||
| match response.status_code: | ||
| case 200: | ||
| token_data = response.json() | ||
| # Convert to our TokenData format | ||
| return { | ||
| "access_token": token_data["access_token"], | ||
| "token_type": token_data.get("token_type", "Bearer"), | ||
| "expires_in": token_data.get("expires_in", 3600), | ||
| "scope": token_data.get("scope", scope), | ||
| # Client credentials flow doesn't provide these, but we need them for compatibility | ||
| "refresh_token": "", | ||
| "id_token": "", | ||
| } | ||
| case 400: | ||
| console.error( | ||
| "Invalid client credentials or request parameters." | ||
| ) | ||
| return None | ||
| case 401: | ||
| console.error("Unauthorized: Invalid client credentials.") | ||
| return None | ||
| case _: | ||
| console.error( | ||
| f"Authentication failed: {response.status_code} - {response.text}" | ||
| ) | ||
| return None | ||
|
|
||
| except httpx.RequestError as e: | ||
| console.error(f"Network error during authentication: {e}") | ||
| return None | ||
| except Exception as e: | ||
| console.error(f"Unexpected error during authentication: {e}") | ||
| return None | ||
|
|
||
| def setup_environment(self, token_data: TokenData, base_url: str): | ||
| """Setup environment variables for client credentials authentication. | ||
|
|
||
| Args: | ||
| token_data: The token data from authentication | ||
| base_url: The base URL for the UiPath instance | ||
| """ | ||
| parsed_access_token = parse_access_token(token_data["access_token"]) | ||
|
|
||
| env_vars = { | ||
| "UIPATH_ACCESS_TOKEN": token_data["access_token"], | ||
| "UIPATH_URL": base_url, | ||
| "UIPATH_ORGANIZATION_ID": parsed_access_token.get("prt_id", ""), | ||
| "UIPATH_TENANT_ID": "", | ||
| } | ||
|
|
||
| update_env_file(env_vars) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] This inner
if base_url:check is redundant becausebase_urlwas already validated above. You can remove this condition to simplify the logic.