Debian Codegraph @

azure-kusto-data/azure/kusto/data/_token_providers.py

raw
1 # Copyright (c) Microsoft Corporation.
2 # Licensed under the MIT License
3 import abc
4 import asyncio
5 import inspect
6 import time
7 from datetime import datetime
8 from threading import Lock
9 from typing import Callable, Coroutine, List, Optional, Any
10
11 import requests
12 from azure.core.exceptions import ClientAuthenticationError
13 from azure.core.tracing import SpanKind
14 from azure.core.tracing.decorator import distributed_trace
15 from azure.core.tracing.decorator_async import distributed_trace_async
16 from azure.identity import AzureCliCredential, ManagedIdentityCredential, DeviceCodeCredential
17 from msal import ConfidentialClientApplication, PublicClientApplication
18
19 from ._cloud_settings import CloudInfo, CloudSettings
20 from ._telemetry import MonitoredActivity
21 from .exceptions import KustoAioSyntaxError, KustoAsyncUsageError, KustoClientError
22
23 DeviceCallbackType = Callable[[str, str, datetime], None]
24 """A callback enabling control of how authentication
25 instructions are presented. Must accept arguments (``verification_uri``, ``user_code``, ``expires_on``):
26
27 - ``verification_uri`` (str) the URL the user must visit
28 - ``user_code`` (str) the code the user must enter there
29 - ``expires_on`` (datetime.datetime) the UTC time at which the code will expire
30 If this argument isn't provided, the credential will print instructions to stdout."""
31
32 try:
33 from asgiref.sync import sync_to_async
34 except ImportError:
35
36 def sync_to_async(f):
37 raise KustoAioSyntaxError()
38
39
40 try:
41 from azure.identity.aio import (
42 ManagedIdentityCredential as AsyncManagedIdentityCredential,
43 AzureCliCredential as AsyncAzureCliCredential,
44 DefaultAzureCredential as AsyncDefaultAzureCredential,
45 )
46
47 from azure.core.credentials_async import AsyncTokenCredential
48 except ImportError:
49 # These are here in case the user doesn't have the aio optional dependency installed, but still tries to use async.
50 # They will give them a useful error message, and will appease linters.
51 class AsyncManagedIdentityCredential:
52 def __init__(self):
53 raise KustoAioSyntaxError()
54
55 class AsyncAzureCliCredential:
56 def __init__(self):
57 raise KustoAioSyntaxError()
58
59 class AsyncDefaultAzureCredential:
60 def __init__(self):
61 raise KustoAioSyntaxError()
62
63 class AsyncTokenCredential:
64 def __init__(self):
65 raise KustoAioSyntaxError()
66
67
68 # constant key names and values used throughout the code
69 class TokenConstants:
70 BEARER_TYPE = "Bearer"
71 MSAL_TOKEN_TYPE = "token_type"
72 MSAL_ACCESS_TOKEN = "access_token"
73 MSAL_ERROR = "error"
74 MSAL_ERROR_DESCRIPTION = "error_description"
75 MSAL_PRIVATE_CERT = "private_key"
76 MSAL_THUMBPRINT = "thumbprint"
77 MSAL_PUBLIC_CERT = "public_certificate"
78 MSAL_DEVICE_MSG = "message"
79 MSAL_DEVICE_URI = "verification_uri"
80 MSAL_INTERACTIVE_PROMPT = "select_account"
81 AZ_TOKEN_TYPE = "tokenType"
82 AZ_ACCESS_TOKEN = "accessToken"
83
84
85 class TokenProviderBase(abc.ABC):
86 """
87 This base class abstracts token acquisition for all implementations.
88 The class is build for Lazy initialization, so that the first call, take on instantiation of 'heavy' long-lived class members
89 """
90
91 _initialized: bool = False
92 _resources_initialized: bool = False
93
94 def __init__(self, is_async: bool = False):
95 self._proxy_dict: Optional[str, str] = None
96 self._session: Optional[requests.Session] = None
97 self.is_async = is_async
98
99 if is_async:
100 self._async_lock = asyncio.Lock()
101 else:
102 self._lock = Lock()
103
104 def close(self):
105 pass
106
107 async def close_async(self):
108 pass
109
110 def _init_once(self, init_only_resources=False):
111 if self._initialized:
112 return
113
114 with self._lock:
115 if self._initialized:
116 return
117
118 if not self._resources_initialized:
119 self._init_resources()
120 self._resources_initialized = True
121
122 if init_only_resources:
123 return
124
125 self._init_impl()
126 self._initialized = True
127
128 async def _init_once_async(self, init_only_resources=False):
129 if self._initialized:
130 return
131
132 async with self._async_lock:
133 if self._initialized:
134 return
135
136 if not self._resources_initialized:
137 await sync_to_async(self._init_resources)()
138 self._resources_initialized = True
139
140 if init_only_resources:
141 return
142
143 self._init_impl()
144 self._initialized = True
145
146 def _init_resources(self):
147 pass
148
149 def get_token(self):
150 """Get a token silently from cache or authenticate if cached token is not found"""
151
152 @distributed_trace(name_of_span=f"{self.name()}.get_token", tracing_attributes=self.context(), kind=SpanKind.CLIENT)
153 def _get_token():
154 if self.is_async:
155 raise KustoAsyncUsageError("get_token", self.is_async)
156 self._init_once()
157
158 token = self._get_token_from_cache_impl()
159 if token is None:
160 with self._lock:
161 token = MonitoredActivity.invoke(self._get_token_impl, name_of_span=f"{self.name()}.get_token_impl", tracing_attributes=self.context())
162 return self._valid_token_or_throw(token)
163
164 return _get_token()
165
166 def context(self) -> dict:
167 if self.is_async:
168 raise KustoAsyncUsageError("context", self.is_async)
169 self._init_once(init_only_resources=True)
170 return self._context_impl()
171
172 async def context_async(self) -> dict:
173 if not self.is_async:
174 raise KustoAsyncUsageError("context_async", self.is_async)
175
176 await self._init_once_async(init_only_resources=True)
177 return self._context_impl()
178
179 async def get_token_async(self):
180 """Get a token asynchronously silently from cache or authenticate if cached token is not found"""
181
182 context = await self.context_async()
183
184 @distributed_trace_async(name_of_span=f"{self.name()}.get_token_async", tracing_attributes=context, kind=SpanKind.CLIENT)
185 async def _get_token_async():
186 if not self.is_async:
187 raise KustoAsyncUsageError("get_token_async", self.is_async)
188
189 await self._init_once_async()
190
191 token = self._get_token_from_cache_impl()
192
193 if token is None:
194 async with self._async_lock:
195 token = await MonitoredActivity.invoke_async(
196 self._get_token_impl_async, name_of_span=f"{self.name()}.get_token_impl_async", tracing_attributes=context
197 )
198
199 return self._valid_token_or_throw(token)
200
201 return await _get_token_async()
202
203 def __enter__(self):
204 return self
205
206 def __exit__(self, exc_type, exc_val, exc_tb):
207 self.close()
208
209 async def __aenter__(self):
210 return self
211
212 async def __aexit__(self, exc_type, exc_val, exc_tb):
213 await self.close_async()
214
215 @staticmethod
216 @abc.abstractmethod
217 def name() -> str:
218 """return the provider class name"""
219 pass
220
221 @abc.abstractmethod
222 def _context_impl(self) -> dict:
223 """return a secret-free context for error reporting"""
224 pass
225
226 @abc.abstractmethod
227 def _init_impl(self):
228 """Implement any "heavy" first time initializations here"""
229 pass
230
231 @abc.abstractmethod
232 def _get_token_impl(self) -> Optional[dict]:
233 """implement actual token acquisition here"""
234 pass
235
236 async def _get_token_impl_async(self) -> Optional[dict]:
237 """implement actual token acquisition here"""
238 return await sync_to_async(self._get_token_impl)()
239
240 @abc.abstractmethod
241 def _get_token_from_cache_impl(self) -> Optional[dict]:
242 """Implement cache checks here, return None if cache check fails"""
243 pass
244
245 @staticmethod
246 def _valid_token_or_none(token: dict) -> Optional[dict]:
247 if token is None or TokenConstants.MSAL_ERROR in token:
248 return None
249 return token
250
251 def _valid_token_or_throw(self, token: dict, context: str = "") -> dict:
252 if token is None:
253 raise KustoClientError(self.name() + " - failed to obtain a token. " + context)
254
255 if TokenConstants.MSAL_ERROR in token:
256 message = self.name() + " - failed to obtain a token. " + context + "\n" + token[TokenConstants.MSAL_ERROR]
257 if TokenConstants.MSAL_ERROR_DESCRIPTION in token:
258 message = message + "\n" + token[TokenConstants.MSAL_ERROR_DESCRIPTION]
259
260 raise KustoClientError(message)
261
262 return token
263
264 def set_proxy(self, proxy_url: str):
265 self._proxy_dict = {"http": proxy_url, "https": proxy_url}
266
267 def set_session(self, session: requests.Session):
268 self._session = session
269
270
271 class CloudInfoTokenProvider(TokenProviderBase, abc.ABC):
272 _cloud_info: Optional[CloudInfo]
273 _scopes = List[str]
274 _kusto_uri: str
275
276 def __init__(self, kusto_uri: str, is_async: bool = False):
277 super().__init__(is_async)
278 self._kusto_uri = kusto_uri
279
280 def _init_resources(self):
281 if self._kusto_uri is not None:
282 self._cloud_info = CloudSettings.get_cloud_info_for_cluster(self._kusto_uri, self._proxy_dict, self._session)
283 resource_uri = self._cloud_info.kusto_service_resource_id
284 if self._cloud_info.login_mfa_required:
285 resource_uri = resource_uri.replace(".kusto.", ".kustomfa.")
286
287 self._scopes = [resource_uri + "/.default"]
288
289
290 class BasicTokenProvider(TokenProviderBase):
291 """Basic Token Provider keeps and returns a token received on construction"""
292
293 def __init__(self, token: str, is_async: bool = False):
294 super().__init__(is_async)
295 self._token = token
296
297 @staticmethod
298 def name() -> str:
299 return "BasicTokenProvider"
300
301 def _context_impl(self) -> dict:
302 return {"authority": self.name()}
303
304 def _init_impl(self):
305 pass
306
307 def _get_token_impl(self) -> Optional[dict]:
308 return None
309
310 def _get_token_from_cache_impl(self) -> dict:
311 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: self._token}
312
313
314 class CallbackTokenProvider(TokenProviderBase):
315 """Callback Token Provider generates a token based on a callback function provided by the caller"""
316
317 def __init__(
318 self, token_callback: Optional[Callable[[], str]], async_token_callback: Optional[Callable[[], Coroutine[None, None, str]]], is_async: bool = False
319 ):
320 super().__init__(is_async)
321 self._token_callback = token_callback
322 self._async_token_callback = async_token_callback
323
324 @staticmethod
325 def name() -> str:
326 return "CallbackTokenProvider"
327
328 def _context_impl(self) -> dict:
329 return {"authority": self.name()}
330
331 def _init_impl(self):
332 pass
333
334 @staticmethod
335 def _build_response(caller_token) -> dict:
336 if not isinstance(caller_token, str):
337 raise KustoClientError("Token provider returned something that is not a string [" + str(type(caller_token)) + "]")
338
339 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: caller_token}
340
341 def _get_token_impl(self) -> Optional[dict]:
342 if self._token_callback is None:
343 raise KustoClientError("token_callback is None, can't retrieve token")
344 return self._build_response(self._token_callback())
345
346 async def _get_token_impl_async(self) -> Optional[dict]:
347 if self._async_token_callback is None:
348 return await super()._get_token_impl_async()
349 return self._build_response(await self._async_token_callback())
350
351 def _get_token_from_cache_impl(self) -> Optional[dict]:
352 return None
353
354
355 class MsiTokenProvider(CloudInfoTokenProvider):
356 """
357 MSI Token Provider obtains a token from the MSI endpoint
358 The args parameter is a dictionary conforming with the ManagedIdentityCredential initializer API arguments
359 """
360
361 def __init__(self, kusto_uri: str, msi_args: dict = None, is_async: bool = False):
362 super().__init__(kusto_uri, is_async)
363 self._msi_args: dict = msi_args
364 self._msi_auth_context: Optional[ManagedIdentityCredential] = None
365 self._msi_auth_context_async: Optional[AsyncManagedIdentityCredential] = None
366
367 @staticmethod
368 def name() -> str:
369 return "MsiTokenProvider"
370
371 def _context_impl(self) -> dict:
372 context = self._msi_args.copy()
373 context["authority"] = self.name()
374 return context
375
376 def _init_impl(self):
377 pass
378
379 def _get_token_impl(self) -> Optional[dict]:
380 try:
381 if self._msi_auth_context is None:
382 self._msi_auth_context = ManagedIdentityCredential(**self._msi_args)
383
384 msi_token = self._msi_auth_context.get_token(self._scopes[0])
385 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: msi_token.token}
386 except ClientAuthenticationError as e:
387 raise KustoClientError("Failed to initialize MSI ManagedIdentityCredential with [{0}]\n{1}".format(self._msi_args, e))
388 except Exception as e:
389 raise KustoClientError("Failed to obtain MSI token for '{0}' with [{1}]\n{2}".format(self._kusto_uri, self._msi_args, e))
390
391 async def _get_token_impl_async(self) -> Optional[dict]:
392 try:
393 if self._msi_auth_context_async is None:
394 self._msi_auth_context_async = AsyncManagedIdentityCredential(**self._msi_args)
395
396 msi_token = await self._msi_auth_context_async.get_token(self._scopes[0])
397 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: msi_token.token}
398 except ClientAuthenticationError as e:
399 raise KustoClientError("Failed to initialize MSI async ManagedIdentityCredential with [{0}]\n{1}".format(self._msi_args, e))
400 except Exception as e:
401 raise KustoClientError("Failed to obtain MSI token for '{0}' with [{1}]\n{2}".format(self._kusto_uri, self._msi_args, e))
402
403 def _get_token_from_cache_impl(self) -> Optional[dict]:
404 return None
405
406 def close(self):
407 if self._msi_auth_context is not None:
408 self._msi_auth_context.close()
409 if self._msi_auth_context_async is not None:
410 raise KustoAsyncUsageError("Can't close async token provider with sync close", self.is_async)
411
412 async def close_async(self):
413 if self._msi_auth_context is not None:
414 await sync_to_async(self._msi_auth_context.close())
415
416 if self._msi_auth_context_async is not None:
417 await self._msi_auth_context_async.close()
418
419
420 class AzCliTokenProvider(CloudInfoTokenProvider):
421 """AzCli Token Provider obtains a refresh token from the AzCli cache and uses it to authenticate with MSAL"""
422
423 def __init__(self, kusto_uri: str, is_async: bool = False):
424 super().__init__(kusto_uri, is_async)
425 self._az_auth_context = None
426 self._az_auth_context_async = None
427 self._az_token = None
428
429 @staticmethod
430 def name() -> str:
431 return "AzCliTokenProvider"
432
433 def _context_impl(self) -> dict:
434 return {"authority:": self.name()}
435
436 def _init_impl(self):
437 pass
438
439 def _get_token_impl(self) -> Optional[dict]:
440 try:
441 if self._az_auth_context is None:
442 self._az_auth_context = AzureCliCredential()
443
444 self._az_token = self._az_auth_context.get_token(self._scopes[0])
445 return {TokenConstants.AZ_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.AZ_ACCESS_TOKEN: self._az_token.token}
446 except Exception as e:
447 raise KustoClientError(
448 "Failed to obtain Az Cli token for '{0}'.\nPlease be sure AzCli version 2.3.0 and above is intalled.\n{1}".format(self._kusto_uri, e)
449 )
450
451 async def _get_token_impl_async(self) -> Optional[dict]:
452 try:
453 if self._az_auth_context_async is None:
454 self._az_auth_context_async = AsyncAzureCliCredential()
455
456 self._az_token = await self._az_auth_context_async.get_token(self._scopes[0])
457 return {TokenConstants.AZ_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.AZ_ACCESS_TOKEN: self._az_token.token}
458 except Exception as e:
459 raise KustoClientError(
460 "Failed to obtain Az Cli token for '{0}'.\nPlease be sure AzCli version 2.3.0 and above is installed.\n{1}".format(self._kusto_uri, e)
461 )
462
463 def _get_token_from_cache_impl(self) -> Optional[dict]:
464 if self._az_token is not None:
465 # A token is considered valid if it is due to expire in no less than 10 minutes
466 cur_time = time.time()
467 if (self._az_token.expires_on - 600) > cur_time:
468 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: self._az_token.token}
469
470 return None
471
472 def close(self):
473 if self._az_auth_context is not None:
474 self._az_auth_context.close()
475 if self._az_auth_context_async is not None:
476 raise KustoAsyncUsageError("Can't close async token provider with sync close", self.is_async)
477
478 async def close_async(self):
479 if self._az_auth_context is not None:
480 await sync_to_async(self._az_auth_context.close())
481
482 if self._az_auth_context_async is not None:
483 await self._az_auth_context_async.close()
484
485
486 class UserPassTokenProvider(CloudInfoTokenProvider):
487 """Acquire a token from MSAL with username and password"""
488
489 def __init__(self, kusto_uri: str, authority_id: str, username: str, password: str, is_async: bool = False):
490 super().__init__(kusto_uri, is_async)
491 self._msal_client = None
492 self._auth = authority_id
493 self._user = username
494 self._pass = password
495
496 @staticmethod
497 def name() -> str:
498 return "UserPassTokenProvider"
499
500 def _context_impl(self) -> dict:
501 return {"authority": self._cloud_info.authority_uri(self._auth), "client_id": self._cloud_info.kusto_client_app_id, "username": self._user}
502
503 def _init_impl(self):
504 self._msal_client = PublicClientApplication(
505 client_id=self._cloud_info.kusto_client_app_id, authority=self._cloud_info.authority_uri(self._auth), proxies=self._proxy_dict
506 )
507
508 def _get_token_impl(self) -> Optional[dict]:
509 token = self._msal_client.acquire_token_by_username_password(username=self._user, password=self._pass, scopes=self._scopes)
510 return self._valid_token_or_throw(token)
511
512 def _get_token_from_cache_impl(self) -> dict:
513 account = None
514 if self._user is not None:
515 accounts = self._msal_client.get_accounts(self._user)
516 if len(accounts) > 0:
517 account = accounts[0]
518
519 token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=account)
520 return self._valid_token_or_none(token)
521
522
523 class InteractiveLoginTokenProvider(CloudInfoTokenProvider):
524 """Acquire a token from MSAL with Device Login flow"""
525
526 def __init__(
527 self,
528 kusto_uri: str,
529 authority_id: str,
530 login_hint: Optional[str] = None,
531 domain_hint: Optional[str] = None,
532 is_async: bool = False,
533 ):
534 super().__init__(kusto_uri, is_async)
535 self._msal_client = None
536 self._auth = authority_id
537 self._login_hint = login_hint
538 self._domain_hint = domain_hint
539 self._account = None
540
541 @staticmethod
542 def name() -> str:
543 return "InteractiveLoginTokenProvider"
544
545 def _context_impl(self) -> dict:
546 return {"authority": self._cloud_info.authority_uri(self._auth), "client_id": self._cloud_info.kusto_client_app_id}
547
548 def _init_impl(self):
549 self._msal_client = PublicClientApplication(
550 client_id=self._cloud_info.kusto_client_app_id, authority=self._cloud_info.authority_uri(self._auth), proxies=self._proxy_dict
551 )
552
553 def _get_token_impl(self) -> Optional[dict]:
554 token = self._msal_client.acquire_token_interactive(
555 scopes=self._scopes, prompt=TokenConstants.MSAL_INTERACTIVE_PROMPT, login_hint=self._login_hint, domain_hint=self._domain_hint
556 )
557 return self._valid_token_or_throw(token)
558
559 def _get_token_from_cache_impl(self) -> dict:
560 account = None
561 accounts = self._msal_client.get_accounts(self._login_hint)
562 if len(accounts) > 0:
563 account = accounts[0]
564
565 token = self._msal_client.acquire_token_silent(scopes=self._scopes, account=account)
566 return self._valid_token_or_none(token)
567
568
569 class ApplicationKeyTokenProvider(CloudInfoTokenProvider):
570 """Acquire a token from MSAL with application Id and Key"""
571
572 def __init__(self, kusto_uri: str, authority_id: str, app_client_id: str, app_key: str, is_async: bool = False):
573 super().__init__(kusto_uri, is_async)
574 self._msal_client = None
575 self._app_client_id = app_client_id
576 self._app_key = app_key
577 self._auth = authority_id
578
579 @staticmethod
580 def name() -> str:
581 return "ApplicationKeyTokenProvider"
582
583 def _context_impl(self) -> dict:
584 return {"authority": self._cloud_info.authority_uri(self._auth), "client_id": self._app_client_id}
585
586 def _init_impl(self):
587 self._msal_client = ConfidentialClientApplication(
588 client_id=self._app_client_id, client_credential=self._app_key, authority=self._cloud_info.authority_uri(self._auth), proxies=self._proxy_dict
589 )
590
591 def _get_token_impl(self) -> Optional[dict]:
592 token = self._msal_client.acquire_token_for_client(scopes=self._scopes)
593 return self._valid_token_or_throw(token)
594
595 def _get_token_from_cache_impl(self) -> None:
596 return None
597
598
599 class ApplicationCertificateTokenProvider(CloudInfoTokenProvider):
600 """
601 Acquire a token from MSAL using application certificate
602 Passing the public certificate is optional and will result in Subject Name & Issuer Authentication
603 """
604
605 def __init__(
606 self,
607 kusto_uri: str,
608 client_id: str,
609 authority_id: str,
610 private_cert: str,
611 thumbprint: str,
612 public_cert: str = None,
613 is_async: bool = False,
614 ):
615 super().__init__(kusto_uri, is_async)
616 self._msal_client = None
617 self._auth = authority_id
618 self._client_id = client_id
619 self._cert_credentials = {TokenConstants.MSAL_PRIVATE_CERT: private_cert, TokenConstants.MSAL_THUMBPRINT: thumbprint}
620 if public_cert is not None:
621 self._cert_credentials[TokenConstants.MSAL_PUBLIC_CERT] = public_cert
622
623 @staticmethod
624 def name() -> str:
625 return "ApplicationCertificateTokenProvider"
626
627 def _context_impl(self) -> dict:
628 return {
629 "authority": self._cloud_info.authority_uri(self._auth),
630 "client_id": self._client_id,
631 "thumbprint": self._cert_credentials[TokenConstants.MSAL_THUMBPRINT],
632 }
633
634 def _init_impl(self):
635 self._msal_client = ConfidentialClientApplication(
636 client_id=self._client_id, client_credential=self._cert_credentials, authority=self._cloud_info.authority_uri(self._auth), proxies=self._proxy_dict
637 )
638
639 def _get_token_impl(self) -> Optional[dict]:
640 token = self._msal_client.acquire_token_for_client(scopes=self._scopes)
641 return self._valid_token_or_throw(token)
642
643 def _get_token_from_cache_impl(self) -> None:
644 return None
645
646
647 class AzureIdentityTokenCredentialProvider(CloudInfoTokenProvider):
648 """Acquire a token using an Azure Identity credential"""
649
650 def __init__(
651 self,
652 kusto_uri: str,
653 is_async: bool = False,
654 credential: Optional[Any] = None,
655 credential_from_login_endpoint: Optional[Callable[[str], Any]] = None,
656 ):
657 super().__init__(kusto_uri, is_async)
658
659 self.credential = credential
660 self.credential_from_login_endpoint = credential_from_login_endpoint
661
662 if self.credential is None and self.credential_from_login_endpoint is None:
663 raise KustoClientError("Either a credential or a credential_from_login_endpoint must be provided")
664
665 @staticmethod
666 def name() -> str:
667 return "AzureIdentityTokenProvider"
668
669 def _context_impl(self) -> dict:
670 return {"credential": self.credential}
671
672 def _init_impl(self):
673 if self.credential is None:
674 self.credential = self.credential_from_login_endpoint(self._cloud_info.login_endpoint)
675
676 def _get_token_impl(self) -> Optional[dict]:
677 t = self.credential.get_token(self._scopes[0])
678 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: t.token}
679
680 async def _get_token_impl_async(self) -> Optional[dict]:
681 # check if get_token is async
682 if inspect.iscoroutinefunction(self.credential.get_token):
683 t = await self.credential.get_token(self._scopes[0])
684 else:
685 t = await sync_to_async(self.credential.get_token)(self._scopes[0])
686 return {TokenConstants.MSAL_TOKEN_TYPE: TokenConstants.BEARER_TYPE, TokenConstants.MSAL_ACCESS_TOKEN: t.token}
687
688 def _get_token_from_cache_impl(self) -> Optional[dict]:
689 return None
690
691 def close(self):
692 if self.credential is not None:
693 if inspect.iscoroutinefunction(self.credential.close):
694 raise KustoAsyncUsageError("Can't close async token provider with sync close", self.is_async)
695 else:
696 self.credential.close()
697 self.credential = None
698 self.credential_from_login_endpoint = None
699
700 async def close_async(self):
701 if self.credential is not None:
702 if inspect.iscoroutinefunction(self.credential.close):
703 await self.credential.close()
704 else:
705 await sync_to_async(self.credential.close)()
706 self.credential = None
707 self.credential_from_login_endpoint = None
708
709
710 class DeviceLoginTokenProvider(AzureIdentityTokenCredentialProvider):
711 """Acquire a token from MSAL with Device Login flow"""
712
713 def __init__(self, kusto_uri: str, authority_id: str, device_code_callback: DeviceCallbackType = None, is_async: bool = False):
714 self._msal_client = None
715 self._auth = authority_id
716 self._account = None
717 self._device_code_callback = device_code_callback
718
719 def credential_from_login_endpoint(endpoint: str):
720 cred = DeviceCodeCredential(
721 authority=endpoint,
722 tenant_id=self._auth,
723 client_id=self._cloud_info.kusto_client_app_id,
724 prompt_callback=self._device_code_callback,
725 )
726
727 return cred
728
729 super().__init__(kusto_uri, is_async, credential_from_login_endpoint=credential_from_login_endpoint)
730
731 @staticmethod
732 def name() -> str:
733 return "DeviceLoginTokenProvider"
734
735 def _context_impl(self) -> dict:
736 return {"authority": self._cloud_info.authority_uri(self._auth), "client_id": self._cloud_info.kusto_client_app_id}