|
| 1 | +import json |
| 2 | +from collections.abc import Generator |
| 3 | +from typing import Any |
| 4 | +from urllib.parse import urlparse |
| 5 | + |
| 6 | +import requests |
| 7 | +from pydantic import BaseModel |
| 8 | + |
| 9 | +from onyx.llm.interfaces import LLM |
| 10 | +from onyx.llm.models import PreviousMessage |
| 11 | +from onyx.llm.utils import message_to_string |
| 12 | +from onyx.prompts.constants import GENERAL_SEP_PAT |
| 13 | +from onyx.tools.base_tool import BaseTool |
| 14 | +from onyx.tools.models import ToolResponse |
| 15 | +from onyx.utils.logger import setup_logger |
| 16 | +from onyx.utils.special_types import JSON_ro |
| 17 | + |
| 18 | + |
| 19 | +logger = setup_logger() |
| 20 | + |
| 21 | + |
| 22 | +OKTA_PROFILE_RESPONSE_ID = "okta_profile" |
| 23 | + |
| 24 | +OKTA_TOOL_DESCRIPTION = """ |
| 25 | +The Okta profile tool can retrieve user profile information from Okta including: |
| 26 | +- User ID, status, creation date |
| 27 | +- Profile details like name, email, department, location, title, manager, and more |
| 28 | +- Account status and activity |
| 29 | +""" |
| 30 | + |
| 31 | + |
| 32 | +class OIDCConfig(BaseModel): |
| 33 | + issuer: str |
| 34 | + jwks_uri: str | None = None |
| 35 | + userinfo_endpoint: str | None = None |
| 36 | + introspection_endpoint: str | None = None |
| 37 | + token_endpoint: str | None = None |
| 38 | + |
| 39 | + |
| 40 | +class OktaProfileTool(BaseTool): |
| 41 | + _NAME = "get_okta_profile" |
| 42 | + _DESCRIPTION = "This tool is used to get the user's profile information." |
| 43 | + _DISPLAY_NAME = "Okta Profile" |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + access_token: str, |
| 48 | + client_id: str, |
| 49 | + client_secret: str, |
| 50 | + openid_config_url: str, |
| 51 | + okta_api_token: str, |
| 52 | + request_timeout_sec: int = 15, |
| 53 | + ) -> None: |
| 54 | + self.access_token = access_token |
| 55 | + self.client_id = client_id |
| 56 | + self.client_secret = client_secret |
| 57 | + self.openid_config_url = openid_config_url |
| 58 | + self.request_timeout_sec = request_timeout_sec |
| 59 | + |
| 60 | + # Extract Okta org URL from OpenID config URL using URL parsing |
| 61 | + # OpenID config URL format: https://{org}.okta.com/.well-known/openid_configuration |
| 62 | + parsed_url = urlparse(self.openid_config_url) |
| 63 | + self.okta_org_url = f"{parsed_url.scheme}://{parsed_url.netloc}" |
| 64 | + self.okta_api_token = okta_api_token |
| 65 | + |
| 66 | + self._oidc_config: OIDCConfig | None = None |
| 67 | + |
| 68 | + @property |
| 69 | + def name(self) -> str: |
| 70 | + return self._NAME |
| 71 | + |
| 72 | + @property |
| 73 | + def description(self) -> str: |
| 74 | + return self._DESCRIPTION |
| 75 | + |
| 76 | + @property |
| 77 | + def display_name(self) -> str: |
| 78 | + return self._DISPLAY_NAME |
| 79 | + |
| 80 | + def tool_definition(self) -> dict: |
| 81 | + return { |
| 82 | + "type": "function", |
| 83 | + "function": { |
| 84 | + "name": self.name, |
| 85 | + "description": self.description, |
| 86 | + "parameters": {"type": "object", "properties": {}, "required": []}, |
| 87 | + }, |
| 88 | + } |
| 89 | + |
| 90 | + def _load_oidc_config(self) -> OIDCConfig: |
| 91 | + if self._oidc_config is not None: |
| 92 | + return self._oidc_config |
| 93 | + |
| 94 | + resp = requests.get(self.openid_config_url, timeout=self.request_timeout_sec) |
| 95 | + resp.raise_for_status() |
| 96 | + data = resp.json() |
| 97 | + self._oidc_config = OIDCConfig(**data) |
| 98 | + logger.debug(f"Loaded OIDC config from {self.openid_config_url}") |
| 99 | + return self._oidc_config |
| 100 | + |
| 101 | + def _call_userinfo(self, access_token: str) -> dict[str, Any] | None: |
| 102 | + try: |
| 103 | + cfg = self._load_oidc_config() |
| 104 | + if not cfg.userinfo_endpoint: |
| 105 | + logger.info("OIDC config missing userinfo_endpoint") |
| 106 | + return None |
| 107 | + headers = {"Authorization": f"Bearer {access_token}"} |
| 108 | + r = requests.get( |
| 109 | + cfg.userinfo_endpoint, headers=headers, timeout=self.request_timeout_sec |
| 110 | + ) |
| 111 | + if r.status_code == 200: |
| 112 | + return r.json() |
| 113 | + logger.info( |
| 114 | + f"userinfo call returned status {r.status_code}: {r.text[:200]}" |
| 115 | + ) |
| 116 | + return None |
| 117 | + except requests.RequestException as e: |
| 118 | + logger.debug(f"userinfo request failed: {e}") |
| 119 | + return None |
| 120 | + |
| 121 | + def _call_introspection(self, access_token: str) -> dict[str, Any] | None: |
| 122 | + try: |
| 123 | + cfg = self._load_oidc_config() |
| 124 | + if not cfg.introspection_endpoint: |
| 125 | + logger.info("OIDC config missing introspection_endpoint") |
| 126 | + return None |
| 127 | + data = { |
| 128 | + "token": access_token, |
| 129 | + "token_type_hint": "access_token", |
| 130 | + } |
| 131 | + auth: tuple[str, str] | None = (self.client_id, self.client_secret) |
| 132 | + r = requests.post( |
| 133 | + cfg.introspection_endpoint, |
| 134 | + data=data, |
| 135 | + auth=auth, |
| 136 | + headers={"Accept": "application/json"}, |
| 137 | + timeout=self.request_timeout_sec, |
| 138 | + ) |
| 139 | + if r.status_code == 200: |
| 140 | + return r.json() |
| 141 | + logger.info( |
| 142 | + f"introspection call returned status {r.status_code}: {r.text[:200]}" |
| 143 | + ) |
| 144 | + return None |
| 145 | + except requests.RequestException as e: |
| 146 | + logger.debug(f"introspection request failed: {e}") |
| 147 | + return None |
| 148 | + |
| 149 | + def _call_users_api(self, uid: str) -> dict[str, Any]: |
| 150 | + """Call Okta Users API to fetch full user profile. |
| 151 | +
|
| 152 | + Requires okta_org_url and okta_api_token to be set. Raises exception on any error. |
| 153 | + """ |
| 154 | + if not self.okta_org_url or not self.okta_api_token: |
| 155 | + raise ValueError( |
| 156 | + "Okta org URL and API token are required for user profile lookup" |
| 157 | + ) |
| 158 | + |
| 159 | + try: |
| 160 | + url = f"{self.okta_org_url.rstrip('/')}/api/v1/users/{uid}" |
| 161 | + headers = {"Authorization": f"SSWS {self.okta_api_token}"} |
| 162 | + r = requests.get(url, headers=headers, timeout=self.request_timeout_sec) |
| 163 | + if r.status_code == 200: |
| 164 | + return r.json() |
| 165 | + raise ValueError( |
| 166 | + f"Okta Users API call failed with status {r.status_code}: {r.text[:200]}" |
| 167 | + ) |
| 168 | + except requests.RequestException as e: |
| 169 | + raise ValueError(f"Okta Users API request failed: {e}") from e |
| 170 | + |
| 171 | + def build_tool_message_content( |
| 172 | + self, *args: ToolResponse |
| 173 | + ) -> str | list[str | dict[str, Any]]: |
| 174 | + # The tool emits a single aggregated packet; pass it through as compact JSON |
| 175 | + profile = args[-1].response if args else {} |
| 176 | + return json.dumps(profile) |
| 177 | + |
| 178 | + def get_args_for_non_tool_calling_llm( |
| 179 | + self, |
| 180 | + query: str, |
| 181 | + history: list[PreviousMessage], |
| 182 | + llm: LLM, |
| 183 | + force_run: bool = False, |
| 184 | + ) -> dict[str, Any] | None: |
| 185 | + if force_run: |
| 186 | + return {} |
| 187 | + |
| 188 | + # Use LLM to determine if this tool should be called based on the query |
| 189 | + prompt = f""" |
| 190 | +You are helping to determine if an Okta profile lookup tool should be called based on a user's query. |
| 191 | +
|
| 192 | +{OKTA_TOOL_DESCRIPTION} |
| 193 | +
|
| 194 | +Query: {query} |
| 195 | +
|
| 196 | +Conversation history: |
| 197 | +{GENERAL_SEP_PAT} |
| 198 | +{history} |
| 199 | +{GENERAL_SEP_PAT} |
| 200 | +
|
| 201 | +Should the Okta profile tool be called for this query? Respond with only "YES" or "NO". |
| 202 | +""".strip() |
| 203 | + response = llm.invoke(prompt) |
| 204 | + if response and "YES" in message_to_string(response).upper(): |
| 205 | + return {} |
| 206 | + |
| 207 | + return None |
| 208 | + |
| 209 | + def run( |
| 210 | + self, override_kwargs: None = None, **llm_kwargs: Any |
| 211 | + ) -> Generator[ToolResponse, None, None]: |
| 212 | + # Try to get UID from userinfo first, then fallback to introspection |
| 213 | + uid_candidate = None |
| 214 | + |
| 215 | + # Try userinfo endpoint first |
| 216 | + userinfo_data = self._call_userinfo(self.access_token) |
| 217 | + if userinfo_data and isinstance(userinfo_data, dict): |
| 218 | + uid_candidate = userinfo_data.get("uid") |
| 219 | + |
| 220 | + # Only try introspection if userinfo didn't provide a UID |
| 221 | + if not uid_candidate: |
| 222 | + introspection_data = self._call_introspection(self.access_token) |
| 223 | + if introspection_data and isinstance(introspection_data, dict): |
| 224 | + uid_candidate = introspection_data.get("uid") |
| 225 | + |
| 226 | + if not uid_candidate: |
| 227 | + raise ValueError( |
| 228 | + "Unable to fetch user profile from Okta. This likely means your Okta " |
| 229 | + "token has expired. Please logout, log back in, and try again." |
| 230 | + ) |
| 231 | + |
| 232 | + # Call Users API to get full profile - this is now required |
| 233 | + users_api_data = self._call_users_api(uid_candidate) |
| 234 | + |
| 235 | + yield ToolResponse( |
| 236 | + id=OKTA_PROFILE_RESPONSE_ID, response=users_api_data["profile"] |
| 237 | + ) |
| 238 | + |
| 239 | + def final_result(self, *args: ToolResponse) -> JSON_ro: |
| 240 | + # Return the single aggregated profile packet |
| 241 | + if not args: |
| 242 | + return {} |
| 243 | + return args[-1].response |
0 commit comments