|
| 1 | +"""This module is an adaptor to the underlying broker. |
| 2 | +It relies on PyMsalRuntime which is the package providing broker's functionality. |
| 3 | +""" |
| 4 | +from threading import Event |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import time |
| 8 | +import uuid |
| 9 | + |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | +try: |
| 13 | + import pymsalruntime # Its API description is available in site-packages/pymsalruntime/PyMsalRuntime.pyi |
| 14 | + pymsalruntime.register_logging_callback(lambda message, level: { # New in pymsalruntime 0.7 |
| 15 | + pymsalruntime.LogLevel.TRACE: logger.debug, # Python has no TRACE level |
| 16 | + pymsalruntime.LogLevel.DEBUG: logger.debug, |
| 17 | + # Let broker's excess info, warning and error logs map into default DEBUG, for now |
| 18 | + #pymsalruntime.LogLevel.INFO: logger.info, |
| 19 | + #pymsalruntime.LogLevel.WARNING: logger.warning, |
| 20 | + #pymsalruntime.LogLevel.ERROR: logger.error, |
| 21 | + pymsalruntime.LogLevel.FATAL: logger.critical, |
| 22 | + }.get(level, logger.debug)(message)) |
| 23 | +except (ImportError, AttributeError): # AttributeError happens when a prior pymsalruntime uninstallation somehow leaved an empty folder behind |
| 24 | + # PyMsalRuntime currently supports these Windows versions, listed in this MSFT internal link |
| 25 | + # https://github.com/AzureAD/microsoft-authentication-library-for-cpp/pull/2406/files |
| 26 | + raise ImportError( # TODO: Remove or adjust this line right before merging this PR |
| 27 | + 'You need to install dependency by: pip install "msal[broker]>=1.20,<2"') |
| 28 | +# It could throw RuntimeError when running on ancient versions of Windows |
| 29 | + |
| 30 | + |
| 31 | +class RedirectUriError(ValueError): |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +class TokenTypeError(ValueError): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +class _CallbackData: |
| 40 | + def __init__(self): |
| 41 | + self.signal = Event() |
| 42 | + self.result = None |
| 43 | + |
| 44 | + def complete(self, result): |
| 45 | + self.signal.set() |
| 46 | + self.result = result |
| 47 | + |
| 48 | + |
| 49 | +def _convert_error(error, client_id): |
| 50 | + context = error.get_context() # Available since pymsalruntime 0.0.4 |
| 51 | + if ( |
| 52 | + "AADSTS50011" in context # In WAM, this could happen on both interactive and silent flows |
| 53 | + or "AADSTS7000218" in context # This "request body must contain ... client_secret" is just a symptom of current app has no WAM redirect_uri |
| 54 | + ): |
| 55 | + raise RedirectUriError( # This would be seen by either the app developer or end user |
| 56 | + "MsalRuntime won't work unless this one more redirect_uri is registered to current app: " |
| 57 | + "ms-appx-web://Microsoft.AAD.BrokerPlugin/{}".format(client_id)) |
| 58 | + # OTOH, AAD would emit other errors when other error handling branch was hit first, |
| 59 | + # so, the AADSTS50011/RedirectUriError is not guaranteed to happen. |
| 60 | + return { |
| 61 | + "error": "broker_error", # Note: Broker implies your device needs to be compliant. |
| 62 | + # You may use "dsregcmd /status" to check your device state |
| 63 | + # https://docs.microsoft.com/en-us/azure/active-directory/devices/troubleshoot-device-dsregcmd |
| 64 | + "error_description": "{}. Status: {}, Error code: {}, Tag: {}".format( |
| 65 | + context, |
| 66 | + error.get_status(), error.get_error_code(), error.get_tag()), |
| 67 | + "_broker_status": error.get_status(), |
| 68 | + "_broker_error_code": error.get_error_code(), |
| 69 | + "_broker_tag": error.get_tag(), |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | +def _read_account_by_id(account_id, correlation_id): |
| 74 | + """Return an instance of MSALRuntimeError or MSALRuntimeAccount, or None""" |
| 75 | + callback_data = _CallbackData() |
| 76 | + pymsalruntime.read_account_by_id( |
| 77 | + account_id, |
| 78 | + correlation_id, |
| 79 | + lambda result, callback_data=callback_data: callback_data.complete(result) |
| 80 | + ) |
| 81 | + callback_data.signal.wait() |
| 82 | + return (callback_data.result.get_error() or callback_data.result.get_account() |
| 83 | + or None) # None happens when the account was not created by broker |
| 84 | + |
| 85 | + |
| 86 | +def _convert_result(result, client_id, expected_token_type=None): # Mimic an on-the-wire response from AAD |
| 87 | + error = result.get_error() |
| 88 | + if error: |
| 89 | + return _convert_error(error, client_id) |
| 90 | + id_token_claims = json.loads(result.get_id_token()) if result.get_id_token() else {} |
| 91 | + account = result.get_account() |
| 92 | + assert account, "Account is expected to be always available" |
| 93 | + # Note: There are more account attribute getters available in pymsalruntime 0.13+ |
| 94 | + return_value = {k: v for k, v in { |
| 95 | + "access_token": result.get_access_token(), |
| 96 | + "expires_in": result.get_access_token_expiry_time() - int(time.time()), # Convert epoch to count-down |
| 97 | + "id_token": result.get_raw_id_token(), # New in pymsalruntime 0.8.1 |
| 98 | + "id_token_claims": id_token_claims, |
| 99 | + "client_info": account.get_client_info(), |
| 100 | + "_account_id": account.get_account_id(), |
| 101 | + "token_type": expected_token_type or "Bearer", # Workaround its absence from broker |
| 102 | + }.items() if v} |
| 103 | + likely_a_cert = return_value["access_token"].startswith("AAAA") # Empirical observation |
| 104 | + if return_value["token_type"].lower() == "ssh-cert" and not likely_a_cert: |
| 105 | + raise TokenTypeError("Broker could not get an SSH Cert: {}...".format( |
| 106 | + return_value["access_token"][:8])) |
| 107 | + granted_scopes = result.get_granted_scopes() # New in pymsalruntime 0.3.x |
| 108 | + if granted_scopes: |
| 109 | + return_value["scope"] = " ".join(granted_scopes) # Mimic the on-the-wire data format |
| 110 | + return return_value |
| 111 | + |
| 112 | + |
| 113 | +def _get_new_correlation_id(): |
| 114 | + return str(uuid.uuid4()) |
| 115 | + |
| 116 | + |
| 117 | +def _enable_msa_pt(params): |
| 118 | + params.set_additional_parameter("msal_request_type", "consumer_passthrough") # PyMsalRuntime 0.8+ |
| 119 | + |
| 120 | + |
| 121 | +def _signin_silently( |
| 122 | + authority, client_id, scopes, correlation_id=None, claims=None, |
| 123 | + enable_msa_pt=False, |
| 124 | + **kwargs): |
| 125 | + params = pymsalruntime.MSALRuntimeAuthParameters(client_id, authority) |
| 126 | + params.set_requested_scopes(scopes) |
| 127 | + if claims: |
| 128 | + params.set_decoded_claims(claims) |
| 129 | + callback_data = _CallbackData() |
| 130 | + for k, v in kwargs.items(): # This can be used to support domain_hint, max_age, etc. |
| 131 | + if v is not None: |
| 132 | + params.set_additional_parameter(k, str(v)) |
| 133 | + if enable_msa_pt: |
| 134 | + _enable_msa_pt(params) |
| 135 | + pymsalruntime.signin_silently( |
| 136 | + params, |
| 137 | + correlation_id or _get_new_correlation_id(), |
| 138 | + lambda result, callback_data=callback_data: callback_data.complete(result)) |
| 139 | + callback_data.signal.wait() |
| 140 | + return _convert_result( |
| 141 | + callback_data.result, client_id, expected_token_type=kwargs.get("token_type")) |
| 142 | + |
| 143 | + |
| 144 | +def _signin_interactively( |
| 145 | + authority, client_id, scopes, |
| 146 | + parent_window_handle, # None means auto-detect for console apps |
| 147 | + prompt=None, # Note: This function does not really use this parameter |
| 148 | + login_hint=None, |
| 149 | + claims=None, |
| 150 | + correlation_id=None, |
| 151 | + enable_msa_pt=False, |
| 152 | + **kwargs): |
| 153 | + params = pymsalruntime.MSALRuntimeAuthParameters(client_id, authority) |
| 154 | + params.set_requested_scopes(scopes) |
| 155 | + params.set_redirect_uri("placeholder") # pymsalruntime 0.1 requires non-empty str, |
| 156 | + # the actual redirect_uri will be overridden by a value hardcoded by the broker |
| 157 | + if prompt: |
| 158 | + if prompt == "select_account": |
| 159 | + if login_hint: |
| 160 | + # FWIW, AAD's browser interactive flow would honor select_account |
| 161 | + # and ignore login_hint in such a case. |
| 162 | + # But pymsalruntime 0.3.x would pop up a meaningless account picker |
| 163 | + # and then force the account_hint user to re-input password. Not what we want. |
| 164 | + # https://identitydivision.visualstudio.com/Engineering/_workitems/edit/1744492 |
| 165 | + login_hint = None # Mimicing the AAD behavior |
| 166 | + logger.warning("Using both select_account and login_hint is ambiguous. Ignoring login_hint.") |
| 167 | + else: |
| 168 | + logger.warning("prompt=%s is not supported by this module", prompt) |
| 169 | + if parent_window_handle is None: |
| 170 | + # This fixes account picker hanging in IDE debug mode on some machines |
| 171 | + params.set_additional_parameter("msal_gui_thread", "true") # Since pymsalruntime 0.8.1 |
| 172 | + if enable_msa_pt: |
| 173 | + _enable_msa_pt(params) |
| 174 | + for k, v in kwargs.items(): # This can be used to support domain_hint, max_age, etc. |
| 175 | + if v is not None: |
| 176 | + params.set_additional_parameter(k, str(v)) |
| 177 | + if claims: |
| 178 | + params.set_decoded_claims(claims) |
| 179 | + callback_data = _CallbackData() |
| 180 | + pymsalruntime.signin_interactively( |
| 181 | + parent_window_handle or pymsalruntime.get_console_window() or pymsalruntime.get_desktop_window(), # Since pymsalruntime 0.2+ |
| 182 | + params, |
| 183 | + correlation_id or _get_new_correlation_id(), |
| 184 | + login_hint, # None value will be accepted since pymsalruntime 0.3+ |
| 185 | + lambda result, callback_data=callback_data: callback_data.complete(result)) |
| 186 | + callback_data.signal.wait() |
| 187 | + return _convert_result( |
| 188 | + callback_data.result, client_id, expected_token_type=kwargs.get("token_type")) |
| 189 | + |
| 190 | + |
| 191 | +def _acquire_token_silently( |
| 192 | + authority, client_id, account_id, scopes, claims=None, correlation_id=None, |
| 193 | + **kwargs): |
| 194 | + # For MSA PT scenario where you use the /organizations, yes, |
| 195 | + # acquireTokenSilently is expected to fail. - Sam Wilson |
| 196 | + correlation_id = correlation_id or _get_new_correlation_id() |
| 197 | + account = _read_account_by_id(account_id, correlation_id) |
| 198 | + if isinstance(account, pymsalruntime.MSALRuntimeError): |
| 199 | + return _convert_error(account, client_id) |
| 200 | + if account is None: |
| 201 | + return |
| 202 | + params = pymsalruntime.MSALRuntimeAuthParameters(client_id, authority) |
| 203 | + params.set_requested_scopes(scopes) |
| 204 | + if claims: |
| 205 | + params.set_decoded_claims(claims) |
| 206 | + for k, v in kwargs.items(): # This can be used to support domain_hint, max_age, etc. |
| 207 | + if v is not None: |
| 208 | + params.set_additional_parameter(k, str(v)) |
| 209 | + callback_data = _CallbackData() |
| 210 | + pymsalruntime.acquire_token_silently( |
| 211 | + params, |
| 212 | + correlation_id, |
| 213 | + account, |
| 214 | + lambda result, callback_data=callback_data: callback_data.complete(result)) |
| 215 | + callback_data.signal.wait() |
| 216 | + return _convert_result( |
| 217 | + callback_data.result, client_id, expected_token_type=kwargs.get("token_type")) |
| 218 | + |
| 219 | + |
| 220 | +def _signout_silently(client_id, account_id, correlation_id=None): |
| 221 | + correlation_id = correlation_id or _get_new_correlation_id() |
| 222 | + account = _read_account_by_id(account_id, correlation_id) |
| 223 | + if isinstance(account, pymsalruntime.MSALRuntimeError): |
| 224 | + return _convert_error(account, client_id) |
| 225 | + if account is None: |
| 226 | + return |
| 227 | + callback_data = _CallbackData() |
| 228 | + pymsalruntime.signout_silently( # New in PyMsalRuntime 0.7 |
| 229 | + client_id, |
| 230 | + correlation_id, |
| 231 | + account, |
| 232 | + lambda result, callback_data=callback_data: callback_data.complete(result)) |
| 233 | + callback_data.signal.wait() |
| 234 | + error = callback_data.result.get_error() |
| 235 | + if error: |
| 236 | + return _convert_error(error, client_id) |
| 237 | + |
0 commit comments