|
| 1 | +""" |
| 2 | +Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +Licensed under the MIT License. |
| 4 | +""" |
| 5 | + |
| 6 | +import logging |
| 7 | +import jwt |
| 8 | +from datetime import datetime, timezone |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +from microsoft_agents.activity import TokenResponse |
| 12 | +from microsoft_agents.hosting.core.errors import ErrorResources |
| 13 | + |
| 14 | +from ...._oauth._flow_state import _FlowStateTag |
| 15 | +from ....turn_context import TurnContext |
| 16 | +from ....storage import Storage |
| 17 | +from ....authorization import Connections |
| 18 | +from ..auth_handler import AuthHandler |
| 19 | +from ._authorization_handler import _AuthorizationHandler |
| 20 | +from .._sign_in_response import _SignInResponse |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +class ConnectorUserAuthorization(_AuthorizationHandler): |
| 26 | + """ |
| 27 | + User Authorization handling for Copilot Studio Connector requests. |
| 28 | + Extracts token from the identity and performs OBO token exchange. |
| 29 | + """ |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, |
| 33 | + storage: Storage, |
| 34 | + connection_manager: Connections, |
| 35 | + auth_handler: Optional[AuthHandler] = None, |
| 36 | + *, |
| 37 | + auth_handler_id: Optional[str] = None, |
| 38 | + auth_handler_settings: Optional[dict] = None, |
| 39 | + **kwargs, |
| 40 | + ) -> None: |
| 41 | + """ |
| 42 | + Creates a new instance of ConnectorUserAuthorization. |
| 43 | +
|
| 44 | + :param storage: The storage system to use for state management. |
| 45 | + :type storage: Storage |
| 46 | + :param connection_manager: The connection manager for OAuth providers. |
| 47 | + :type connection_manager: Connections |
| 48 | + :param auth_handler: Configuration for OAuth provider. |
| 49 | + :type auth_handler: AuthHandler, Optional |
| 50 | + :param auth_handler_id: Optional ID of the auth handler. |
| 51 | + :type auth_handler_id: str, Optional |
| 52 | + :param auth_handler_settings: Optional settings dict for the auth handler. |
| 53 | + :type auth_handler_settings: dict, Optional |
| 54 | + """ |
| 55 | + super().__init__( |
| 56 | + storage, |
| 57 | + connection_manager, |
| 58 | + auth_handler, |
| 59 | + auth_handler_id=auth_handler_id, |
| 60 | + auth_handler_settings=auth_handler_settings, |
| 61 | + **kwargs, |
| 62 | + ) |
| 63 | + |
| 64 | + async def _sign_in( |
| 65 | + self, |
| 66 | + context: TurnContext, |
| 67 | + exchange_connection: Optional[str] = None, |
| 68 | + exchange_scopes: Optional[list[str]] = None, |
| 69 | + ) -> _SignInResponse: |
| 70 | + """ |
| 71 | + For connector requests, there is no separate sign-in flow. |
| 72 | + The token is extracted from the identity. |
| 73 | +
|
| 74 | + :param context: The turn context for the current turn of conversation. |
| 75 | + :type context: TurnContext |
| 76 | + :param exchange_connection: Optional connection name for token exchange. |
| 77 | + :type exchange_connection: Optional[str] |
| 78 | + :param exchange_scopes: Optional list of scopes (unused for connector auth). |
| 79 | + :type exchange_scopes: Optional[list[str]] |
| 80 | + :return: A SignInResponse with the extracted token. |
| 81 | + :rtype: _SignInResponse |
| 82 | + """ |
| 83 | + # Connector auth uses the token from the request, not a separate sign-in flow |
| 84 | + token_response = await self.get_refreshed_token(context) |
| 85 | + return _SignInResponse( |
| 86 | + token_response=token_response, tag=_FlowStateTag.COMPLETE |
| 87 | + ) |
| 88 | + |
| 89 | + async def get_refreshed_token( |
| 90 | + self, |
| 91 | + context: TurnContext, |
| 92 | + exchange_connection: Optional[str] = None, |
| 93 | + exchange_scopes: Optional[list[str]] = None, |
| 94 | + ) -> TokenResponse: |
| 95 | + """ |
| 96 | + Gets the connector user token and optionally exchanges it via OBO. |
| 97 | +
|
| 98 | + :param context: The turn context for the current turn of conversation. |
| 99 | + :type context: TurnContext |
| 100 | + :param exchange_connection: Optional name of the connection to use for token exchange. |
| 101 | + :type exchange_connection: Optional[str], Optional |
| 102 | + :param exchange_scopes: Optional list of scopes to request during token exchange. |
| 103 | + :type exchange_scopes: Optional[list[str]], Optional |
| 104 | + :return: The token response, potentially after OBO exchange. |
| 105 | + :rtype: TokenResponse |
| 106 | + """ |
| 107 | + token_response = self._create_token_response(context) |
| 108 | + |
| 109 | + # Check if token is expired |
| 110 | + if token_response.expiration: |
| 111 | + try: |
| 112 | + # Parse ISO 8601 format |
| 113 | + expiration = datetime.fromisoformat( |
| 114 | + token_response.expiration.replace("Z", "+00:00") |
| 115 | + ) |
| 116 | + if expiration <= datetime.now(timezone.utc): |
| 117 | + raise ValueError( |
| 118 | + f"Unexpected connector token expiration for handler: {self._id}" |
| 119 | + ) |
| 120 | + except (ValueError, AttributeError) as ex: |
| 121 | + logger.error( |
| 122 | + f"Error checking token expiration for handler {self._id}: {ex}" |
| 123 | + ) |
| 124 | + raise |
| 125 | + |
| 126 | + # Perform OBO exchange if configured |
| 127 | + try: |
| 128 | + return await self._handle_obo( |
| 129 | + context, token_response, exchange_connection, exchange_scopes |
| 130 | + ) |
| 131 | + except Exception: |
| 132 | + await self._sign_out(context) |
| 133 | + raise |
| 134 | + |
| 135 | + async def _sign_out(self, context: TurnContext) -> None: |
| 136 | + """ |
| 137 | + Sign-out is a no-op for connector authorization. |
| 138 | +
|
| 139 | + :param context: The turn context for the current turn of conversation. |
| 140 | + :type context: TurnContext |
| 141 | + """ |
| 142 | + # No concept of sign-out with ConnectorAuth |
| 143 | + logger.debug("Sign-out called for ConnectorUserAuthorization (no-op)") |
| 144 | + |
| 145 | + async def _handle_obo( |
| 146 | + self, |
| 147 | + context: TurnContext, |
| 148 | + input_token_response: TokenResponse, |
| 149 | + exchange_connection: Optional[str] = None, |
| 150 | + exchange_scopes: Optional[list[str]] = None, |
| 151 | + ) -> TokenResponse: |
| 152 | + """ |
| 153 | + Exchanges a token for another token with different scopes via OBO flow. |
| 154 | +
|
| 155 | + :param context: The context object for the current turn. |
| 156 | + :type context: TurnContext |
| 157 | + :param input_token_response: The input token to exchange. |
| 158 | + :type input_token_response: TokenResponse |
| 159 | + :param exchange_connection: Optional connection name for exchange. |
| 160 | + :type exchange_connection: Optional[str] |
| 161 | + :param exchange_scopes: Optional scopes for the exchanged token. |
| 162 | + :type exchange_scopes: Optional[list[str]] |
| 163 | + :return: The token response after exchange, or the original if exchange not configured. |
| 164 | + :rtype: TokenResponse |
| 165 | + """ |
| 166 | + if not input_token_response: |
| 167 | + return input_token_response |
| 168 | + |
| 169 | + connection_name = exchange_connection or self._handler.obo_connection_name |
| 170 | + scopes = exchange_scopes or self._handler.scopes |
| 171 | + |
| 172 | + # If OBO is not configured, return token as-is |
| 173 | + if not connection_name or not scopes: |
| 174 | + return input_token_response |
| 175 | + |
| 176 | + # Check if token is exchangeable |
| 177 | + if not input_token_response.is_exchangeable(): |
| 178 | + raise ValueError( |
| 179 | + str(ErrorResources.OboNotExchangeableToken.format(self._id)) |
| 180 | + ) |
| 181 | + |
| 182 | + # Get the connection that supports OBO |
| 183 | + token_provider = self._connection_manager.get_connection(connection_name) |
| 184 | + if not token_provider: |
| 185 | + raise ValueError( |
| 186 | + str( |
| 187 | + ErrorResources.ResourceNotFound.format( |
| 188 | + f"Connection '{connection_name}'" |
| 189 | + ) |
| 190 | + ) |
| 191 | + ) |
| 192 | + |
| 193 | + # Perform the OBO exchange |
| 194 | + # Note: In Python, the acquire_token_on_behalf_of method is on the AccessTokenProviderBase |
| 195 | + token = await token_provider.acquire_token_on_behalf_of( |
| 196 | + scopes=scopes, |
| 197 | + user_assertion=input_token_response.token, |
| 198 | + ) |
| 199 | + return TokenResponse(token=token) if token else None |
| 200 | + |
| 201 | + def _create_token_response(self, context: TurnContext) -> TokenResponse: |
| 202 | + """ |
| 203 | + Creates a TokenResponse from the security token in the turn context identity. |
| 204 | +
|
| 205 | + :param context: The turn context for the current turn of conversation. |
| 206 | + :type context: TurnContext |
| 207 | + :return: A TokenResponse containing the extracted token. |
| 208 | + :rtype: TokenResponse |
| 209 | + :raises ValueError: If the identity doesn't have a security token. |
| 210 | + """ |
| 211 | + if not context.identity or not hasattr(context.identity, "security_token"): |
| 212 | + raise ValueError( |
| 213 | + f"Unexpected connector request - no security token found for handler: {self._id}" |
| 214 | + ) |
| 215 | + |
| 216 | + security_token = context.identity.security_token |
| 217 | + if not security_token: |
| 218 | + raise ValueError( |
| 219 | + f"Unexpected connector request - security token is None for handler: {self._id}" |
| 220 | + ) |
| 221 | + |
| 222 | + token_response = TokenResponse(token=security_token) |
| 223 | + |
| 224 | + # Try to extract expiration and check if exchangeable |
| 225 | + try: |
| 226 | + # TODO: (connector) validate this decoding |
| 227 | + jwt_token = jwt.decode(security_token, options={"verify_signature": False}) |
| 228 | + |
| 229 | + # Set expiration if present |
| 230 | + if "exp" in jwt_token: |
| 231 | + # JWT exp is in Unix timestamp (seconds since epoch) |
| 232 | + expiration = datetime.fromtimestamp(jwt_token["exp"], tz=timezone.utc) |
| 233 | + # Convert to ISO 8601 format |
| 234 | + token_response.expiration = expiration.isoformat() |
| 235 | + |
| 236 | + except Exception as ex: |
| 237 | + logger.warning(f"Failed to parse JWT token for handler {self._id}: {ex}") |
| 238 | + raise ex |
| 239 | + |
| 240 | + return token_response |
0 commit comments