Debian Codegraph @

azure-kusto-data/azure/kusto/data/kcsb.py

raw
1 import dataclasses
2 from enum import unique, Enum
3 from typing import Union, Callable, Coroutine, Optional, Tuple, List, Any, ClassVar
4 from urllib.parse import urlparse
5
6 from ._string_utils import assert_string_is_not_empty
7 from ._token_providers import DeviceCallbackType
8 from .client_details import ClientDetails
9 from .helpers import load_bundled_json
10
11
12 UNSUPPORTED_KEYWORD = "UNSUPPORTED"
13
14
15 @unique
16 class SupportedKeywords(Enum):
17 DATA_SOURCE = "Data Source"
18 INITIAL_CATALOG = "Initial Catalog"
19 FEDERATED_SECURITY = "AAD Federated Security"
20 APPLICATION_CLIENT_ID = "Application Client Id"
21 APPLICATION_KEY = "Application Key"
22 USER_ID = "User ID"
23 PASSWORD = "Password"
24 AUTHORITY_ID = "Authority Id"
25 APPLICATION_TOKEN = "Application Token"
26 USER_TOKEN = "User Token"
27 APPLICATION_CERTIFICATE_BLOB = "Application Certificate Blob"
28 APPLICATION_CERTIFICATE_X5C = "Application Certificate SendX5c"
29 APPLICATION_CERTIFICATE_THUMBPRINT = "Application Certificate Thumbprint"
30 TRACE_APP_NAME = "Application Name for Tracing"
31 TRACE_USER_NAME = "User Name for Tracing"
32
33
34 @unique
35 class UnsupportedKeywords(Enum):
36 DSTS_FEDERATED_SECURITY = "dSTS Federated Security"
37 STREAMING = "Streaming"
38 UNCOMPRESSED = "Uncompressed"
39 ENFORCE_MFA = "EnforceMfa"
40 ACCEPT = "Accept"
41 QUERY_CONSISTENCY = "Query Consistency"
42 DATA_SOURCE_URI = "Data Source Uri"
43 AZURE_REGION = "Azure Region"
44 NAMESPACE = "Namespace"
45 APPLICATION_CERTIFICATE_ISSUER_DISTINGUISHED_NAME = "Application Certificate Issuer Distinguished Name"
46 APPLICATION_CERTIFICATE_SUBJECT_DISTINGUISHED_NAME = "Application Certificate Subject Distinguished Name"
47
48
49 @dataclasses.dataclass(frozen=True)
50 class Keyword:
51 _supported_keywords: ClassVar[List[str]] = [k.value for k in SupportedKeywords]
52 _unsupported_keywords: ClassVar[List[str]] = [k.value for k in UnsupportedKeywords]
53 _lookup: ClassVar[dict]
54
55 name: SupportedKeywords
56 type: str
57 secret: bool
58
59 def is_str_type(self) -> bool:
60 return self.type == "string"
61
62 def is_bool_type(self) -> bool:
63 return self.type == "bool"
64
65 @staticmethod
66 def normalize_string(key: str) -> str:
67 return key.lower().replace(" ", "")
68
69 @classmethod
70 def init_lookup(cls):
71 kcsb_json: dict = load_bundled_json("kcsb.json")
72 lookup = {}
73 for v in kcsb_json["keywords"]:
74 name = v["name"]
75 if name in cls._supported_keywords:
76 keyword = Keyword(SupportedKeywords(name), v["type"], v["secret"])
77 elif name in cls._unsupported_keywords:
78 keyword = UNSUPPORTED_KEYWORD
79 else:
80 raise KeyError(f"Unknown keyword: `{name}`")
81
82 lookup[Keyword.normalize_string(name)] = keyword
83
84 for alias in v["aliases"]:
85 lookup[Keyword.normalize_string(alias)] = keyword
86
87 cls._lookup = lookup
88
89 @classmethod
90 def parse(cls, key: Union[str, SupportedKeywords]) -> "Keyword":
91 if isinstance(key, SupportedKeywords):
92 key = key.value
93
94 normalized = Keyword.normalize_string(key)
95
96 if normalized not in cls._lookup:
97 raise KeyError(f"Unknown keyword: `{key}`")
98
99 if cls._lookup[normalized] == UNSUPPORTED_KEYWORD:
100 raise KeyError(f"Keyword `{key}` is not supported by this SDK")
101
102 return cls._lookup[normalized]
103
104 @classmethod
105 def lookup(cls, key: Union[str, SupportedKeywords]) -> "Keyword":
106 if isinstance(key, SupportedKeywords):
107 key = key.value
108
109 return cls._lookup[Keyword.normalize_string(key)]
110
111
112 Keyword.init_lookup()
113
114
115 class KustoConnectionStringBuilder:
116 """
117 Parses Kusto connection strings.
118 For usages, check out the sample at:
119 https://github.com/Azure/azure-kusto-python/blob/master/azure-kusto-data/tests/sample.py
120 """
121
122 DEFAULT_DATABASE_NAME = "NetDefaultDB"
123
124 interactive_login: bool = False
125 az_cli_login: bool = False
126 device_login: bool = False
127 token_credential_login: bool = False
128
129 device_callback: DeviceCallbackType = None
130 msi_authentication: bool = False
131 msi_parameters: Optional[dict] = None
132
133 token_provider: Optional[Callable[[], str]] = None
134 async_token_provider: Optional[Callable[[], Coroutine[None, None, str]]] = None
135
136 application_for_tracing: Optional[str] = None
137 user_name_for_tracing: Optional[str] = None
138
139 azure_credential: Optional[Any] = None
140 azure_credential_from_login_endpoint: Optional[Any] = None
141
142 application_public_certificate: Optional[str] = None
143
144 def __init__(self, connection_string: str):
145 """
146 Creates new KustoConnectionStringBuilder.
147 :param str connection_string: Kusto connection string should be of the format:
148 https://<clusterName>.kusto.windows.net;AAD User ID="[email protected]";Password=P@ssWord
149 For more information please look at:
150 https://kusto.azurewebsites.net/docs/concepts/kusto_connection_strings.html
151 """
152 assert_string_is_not_empty(connection_string)
153 self._internal_dict = {}
154
155 if connection_string is not None and "=" not in connection_string.partition(";")[0]:
156 connection_string = "Data Source=" + connection_string
157
158 self[SupportedKeywords.AUTHORITY_ID] = "organizations"
159
160 for kvp_string in connection_string.split(";"):
161 key, _, value = kvp_string.partition("=")
162 keyword = Keyword.parse(key)
163
164 value_stripped = value.strip()
165 if keyword.is_str_type():
166 if keyword.name == SupportedKeywords.DATA_SOURCE:
167 self[keyword.name] = value_stripped.rstrip("/")
168 self._parse_data_source(self.data_source)
169 elif keyword.name == SupportedKeywords.TRACE_USER_NAME:
170 self.user_name_for_tracing = value_stripped
171 elif keyword.name == SupportedKeywords.TRACE_APP_NAME:
172 self.application_for_tracing = value_stripped
173 else:
174 self[keyword.name] = value_stripped
175 elif keyword.is_bool_type():
176 if value_stripped in ["True", "true"]:
177 self[keyword.name] = True
178 elif value_stripped in ["False", "false"]:
179 self[keyword.name] = False
180 else:
181 raise KeyError("Expected aad federated security to be bool. Recieved %s" % value)
182
183 if self.initial_catalog is None:
184 self.initial_catalog = self.DEFAULT_DATABASE_NAME
185
186 def __setitem__(self, key: "Union[SupportedKeywords, str]", value: Union[str, bool, dict]):
187 keyword = Keyword.parse(key)
188
189 if value is None:
190 raise TypeError("Value cannot be None.")
191
192 if keyword.is_str_type():
193 self._internal_dict[keyword.name] = value.strip()
194 elif keyword.is_bool_type():
195 if not isinstance(value, bool):
196 raise TypeError("Expected %s to be bool" % key)
197 self._internal_dict[keyword.name] = value
198 else:
199 raise KeyError("KustoConnectionStringBuilder supports only bools and strings.")
200
201 @classmethod
202 def with_aad_user_password_authentication(
203 cls, connection_string: str, user_id: str, password: str, authority_id: str = "organizations"
204 ) -> "KustoConnectionStringBuilder":
205 """
206 Creates a KustoConnection string builder that will authenticate with AAD user name and
207 password.
208 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
209 :param str user_id: AAD user ID.
210 :param str password: Corresponding password of the AAD user.
211 :param str authority_id: optional param. defaults to "organizations"
212 """
213 assert_string_is_not_empty(user_id)
214 assert_string_is_not_empty(password)
215
216 kcsb = cls(connection_string)
217 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
218 kcsb[SupportedKeywords.USER_ID] = user_id
219 kcsb[SupportedKeywords.AUTHORITY_ID] = authority_id
220 kcsb[SupportedKeywords.PASSWORD] = password
221
222 return kcsb
223
224 @classmethod
225 def with_aad_user_token_authentication(cls, connection_string: str, user_token: str) -> "KustoConnectionStringBuilder":
226 """
227 Creates a KustoConnection string builder that will authenticate with AAD application and
228 a certificate credentials.
229 :param str connection_string: Kusto connection string should be of the format:
230 https://<clusterName>.kusto.windows.net
231 :param str user_token: AAD user token.
232 """
233 assert_string_is_not_empty(user_token)
234
235 kcsb = cls(connection_string)
236 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
237 kcsb[SupportedKeywords.USER_TOKEN] = user_token
238
239 return kcsb
240
241 @classmethod
242 def with_aad_application_key_authentication(
243 cls, connection_string: str, aad_app_id: str, app_key: str, authority_id: str
244 ) -> "KustoConnectionStringBuilder":
245 """
246 Creates a KustoConnection string builder that will authenticate with AAD application and key.
247 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
248 :param str aad_app_id: AAD application ID.
249 :param str app_key: Corresponding key of the AAD application.
250 :param str authority_id: Authority id (aka Tenant id) must be provided
251 """
252 assert_string_is_not_empty(aad_app_id)
253 assert_string_is_not_empty(app_key)
254 assert_string_is_not_empty(authority_id)
255
256 kcsb = cls(connection_string)
257 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
258 kcsb[SupportedKeywords.APPLICATION_CLIENT_ID] = aad_app_id
259 kcsb[SupportedKeywords.APPLICATION_KEY] = app_key
260 kcsb[SupportedKeywords.AUTHORITY_ID] = authority_id
261
262 return kcsb
263
264 @classmethod
265 def with_aad_application_certificate_authentication(
266 cls, connection_string: str, aad_app_id: str, certificate: str, thumbprint: str, authority_id: str
267 ) -> "KustoConnectionStringBuilder":
268 """
269 Creates a KustoConnection string builder that will authenticate with AAD application using
270 a certificate.
271 :param str connection_string: Kusto connection string should be of the format:
272 https://<clusterName>.kusto.windows.net
273 :param str aad_app_id: AAD application ID.
274 :param str certificate: A PEM encoded certificate private key.
275 :param str thumbprint: hex encoded thumbprint of the certificate.
276 :param str authority_id: Authority id (aka Tenant id) must be provided
277 """
278 assert_string_is_not_empty(aad_app_id)
279 assert_string_is_not_empty(certificate)
280 assert_string_is_not_empty(thumbprint)
281 assert_string_is_not_empty(authority_id)
282
283 kcsb = cls(connection_string)
284 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
285 kcsb[SupportedKeywords.APPLICATION_CLIENT_ID] = aad_app_id
286 kcsb[SupportedKeywords.APPLICATION_CERTIFICATE_BLOB] = certificate
287 kcsb[SupportedKeywords.APPLICATION_CERTIFICATE_THUMBPRINT] = thumbprint
288 kcsb[SupportedKeywords.AUTHORITY_ID] = authority_id
289
290 return kcsb
291
292 @classmethod
293 def with_aad_application_certificate_sni_authentication(
294 cls, connection_string: str, aad_app_id: str, private_certificate: str, public_certificate: str, thumbprint: str, authority_id: str
295 ) -> "KustoConnectionStringBuilder":
296 """
297 Creates a KustoConnection string builder that will authenticate with AAD application using
298 a certificate Subject Name and Issuer.
299 :param str connection_string: Kusto connection string should be of the format:
300 https://<clusterName>.kusto.windows.net
301 :param str aad_app_id: AAD application ID.
302 :param str private_certificate: A PEM encoded certificate private key.
303 :param str public_certificate: A public certificate matching the provided PEM certificate private key.
304 :param str thumbprint: hex encoded thumbprint of the certificate.
305 :param str authority_id: Authority id (aka Tenant id) must be provided
306 """
307 assert_string_is_not_empty(aad_app_id)
308 assert_string_is_not_empty(private_certificate)
309 assert_string_is_not_empty(public_certificate)
310 assert_string_is_not_empty(thumbprint)
311 assert_string_is_not_empty(authority_id)
312
313 kcsb = cls(connection_string)
314 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
315 kcsb[SupportedKeywords.APPLICATION_CLIENT_ID] = aad_app_id
316 kcsb[SupportedKeywords.APPLICATION_CERTIFICATE_BLOB] = private_certificate
317 kcsb.application_public_certificate = public_certificate
318 kcsb[SupportedKeywords.APPLICATION_CERTIFICATE_THUMBPRINT] = thumbprint
319 kcsb[SupportedKeywords.AUTHORITY_ID] = authority_id
320
321 return kcsb
322
323 @classmethod
324 def with_aad_application_token_authentication(cls, connection_string: str, application_token: str) -> "KustoConnectionStringBuilder":
325 """
326 Creates a KustoConnection string builder that will authenticate with AAD application and
327 an application token.
328 :param str connection_string: Kusto connection string should be of the format:
329 https://<clusterName>.kusto.windows.net
330 :param str application_token: AAD application token.
331 """
332 assert_string_is_not_empty(application_token)
333 kcsb = cls(connection_string)
334 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
335 kcsb[SupportedKeywords.APPLICATION_TOKEN] = application_token
336
337 return kcsb
338
339 @classmethod
340 def with_aad_device_authentication(
341 cls, connection_string: str, authority_id: str = "organizations", callback: DeviceCallbackType = None
342 ) -> "KustoConnectionStringBuilder":
343 """
344 Creates a KustoConnection string builder that will authenticate with AAD application and
345 password.
346 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
347 :param str authority_id: optional param. defaults to "organizations"
348 :param DeviceCallbackType callback: options callback function to be called when authentication is required, accepts three parameters:
349 - ``verification_uri`` (str) the URL the user must visit
350 - ``user_code`` (str) the code the user must enter there
351 - ``expires_on`` (datetime.datetime) the UTC time at which the code will expire
352 """
353 kcsb = cls(connection_string)
354 kcsb.device_login = True
355 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
356 kcsb[SupportedKeywords.AUTHORITY_ID] = authority_id
357 kcsb.device_callback = callback
358
359 return kcsb
360
361 @classmethod
362 def with_az_cli_authentication(cls, connection_string: str) -> "KustoConnectionStringBuilder":
363 """
364 Creates a KustoConnection string builder that will use existing authenticated az cli profile
365 password.
366 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
367 """
368 kcsb = cls(connection_string)
369 kcsb.az_cli_login = True
370 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
371
372 return kcsb
373
374 @classmethod
375 def with_aad_managed_service_identity_authentication(
376 cls, connection_string: str, client_id: str = None, object_id: str = None, msi_res_id: str = None, timeout: int = None
377 ) -> "KustoConnectionStringBuilder":
378 """
379 Creates a KustoConnection string builder that will authenticate with AAD application, using
380 an application token obtained from a Microsoft Service Identity endpoint. An optional user
381 assigned application ID can be added to the token.
382
383 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
384 :param client_id: an optional user assigned identity provided as an Azure ID of a client
385 :param object_id: an optional user assigned identity provided as an Azure ID of an object
386 :param msi_res_id: an optional user assigned identity provided as an Azure ID of an MSI resource
387 :param timeout: an optional timeout (seconds) to wait for an MSI Authentication to occur
388 """
389
390 kcsb = cls(connection_string)
391 params = {}
392 exclusive_pcount = 0
393
394 if timeout is not None:
395 params["connection_timeout"] = timeout
396
397 if client_id is not None:
398 params["client_id"] = client_id
399 exclusive_pcount += 1
400
401 if object_id is not None:
402 # Until we upgrade azure-identity to version 1.4.1, only client_id is excepted as a hint for user managed service identity
403 raise ValueError("User Managed Service Identity with object_id is temporarily not supported by azure identity 1.3.1. Please use client_id instead.")
404 # noinspection PyUnreachableCode
405 params["object_id"] = object_id
406 exclusive_pcount += 1
407
408 if msi_res_id is not None:
409 # Until we upgrade azure-identity to version 1.4.1, only client_id is excepted as a hint for user managed service identity
410 raise ValueError(
411 "User Managed Service Identity with msi_res_id is temporarily not supported by azure identity 1.3.1. Please use client_id instead."
412 )
413 # noinspection PyUnreachableCode
414 params["msi_res_id"] = msi_res_id
415 exclusive_pcount += 1
416
417 if exclusive_pcount > 1:
418 raise ValueError("the following parameters are mutually exclusive and can not be provided at the same time: client_uid, object_id, msi_res_id")
419
420 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
421 kcsb.msi_authentication = True
422 kcsb.msi_parameters = params
423
424 return kcsb
425
426 @classmethod
427 def with_token_provider(cls, connection_string: str, token_provider: Callable[[], str]) -> "KustoConnectionStringBuilder":
428 """
429 Create a KustoConnectionStringBuilder that uses a callback function to obtain a connection token
430 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
431 :param token_provider: a parameterless function that returns a valid bearer token for the relevant kusto resource as a string
432 """
433
434 assert callable(token_provider)
435
436 kcsb = cls(connection_string)
437 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
438 kcsb.token_provider = token_provider
439
440 return kcsb
441
442 @classmethod
443 def with_async_token_provider(
444 cls,
445 connection_string: str,
446 async_token_provider: Callable[[], Coroutine[None, None, str]],
447 ) -> "KustoConnectionStringBuilder":
448 """
449 Create a KustoConnectionStringBuilder that uses an async callback function to obtain a connection token
450 :param str connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
451 :param async_token_provider: a parameterless function that after awaiting returns a valid bearer token for the relevant kusto resource as a string
452 """
453
454 assert callable(async_token_provider)
455
456 kcsb = cls(connection_string)
457 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
458 kcsb.async_token_provider = async_token_provider
459
460 return kcsb
461
462 @classmethod
463 def with_interactive_login(
464 cls, connection_string: str, user_id_hint: Optional[str] = None, tenant_hint: Optional[str] = None
465 ) -> "KustoConnectionStringBuilder":
466 kcsb = cls(connection_string)
467 kcsb.interactive_login = True
468 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
469 if user_id_hint is not None:
470 kcsb[SupportedKeywords.USER_ID] = user_id_hint
471
472 if tenant_hint is not None:
473 kcsb[SupportedKeywords.AUTHORITY_ID] = tenant_hint
474
475 return kcsb
476
477 @classmethod
478 def with_azure_token_credential(
479 cls,
480 connection_string: str,
481 credential: Optional[Any] = None,
482 credential_from_login_endpoint: Optional[Callable[[str], Any]] = None,
483 ) -> "KustoConnectionStringBuilder":
484 """
485 Create a KustoConnectionStringBuilder that uses an azure token credential to obtain a connection token.
486 :param connection_string: Kusto connection string should be of the format: https://<clusterName>.kusto.windows.net
487 :param credential: an optional token credential to use for authentication
488 :param credential_from_login_endpoint: an optional function that returns a token credential for the relevant kusto resource
489 """
490 kcsb = cls(connection_string)
491 kcsb[SupportedKeywords.FEDERATED_SECURITY] = True
492 kcsb.token_credential_login = True
493 kcsb.azure_credential = credential
494 kcsb.azure_credential_from_login_endpoint = credential_from_login_endpoint
495
496 return kcsb
497
498 @classmethod
499 def with_no_authentication(cls, connection_string: str) -> "KustoConnectionStringBuilder":
500 """
501 Create a KustoConnectionStringBuilder that uses no authentication.
502 :param connection_string: Kusto's connection string should be of the format: http://<clusterName>.kusto.windows.net
503 """
504 if not connection_string.startswith("http://"):
505 raise ValueError("Connection string must start with http://")
506 kcsb = cls(connection_string)
507 kcsb[SupportedKeywords.FEDERATED_SECURITY] = False
508
509 return kcsb
510
511 @property
512 def data_source(self) -> Optional[str]:
513 """The URI specifying the Kusto service endpoint.
514 For example, https://kuskus.kusto.windows.net or net.tcp://localhost
515 """
516 return self._internal_dict.get(SupportedKeywords.DATA_SOURCE)
517
518 @property
519 def initial_catalog(self) -> Optional[str]:
520 """The default database to be used for requests.
521 By default, it is set to 'NetDefaultDB'.
522 """
523 return self._internal_dict.get(SupportedKeywords.INITIAL_CATALOG)
524
525 @initial_catalog.setter
526 def initial_catalog(self, value: str) -> None:
527 self._internal_dict[SupportedKeywords.INITIAL_CATALOG] = value
528
529 @property
530 def aad_user_id(self) -> Optional[str]:
531 """The username to use for AAD Federated AuthN."""
532 return self._internal_dict.get(SupportedKeywords.USER_ID)
533
534 @property
535 def application_client_id(self) -> Optional[str]:
536 """The application client id to use for authentication when federated
537 authentication is used.
538 """
539 return self._internal_dict.get(SupportedKeywords.APPLICATION_CLIENT_ID)
540
541 @property
542 def application_key(self) -> Optional[str]:
543 """The application key to use for authentication when federated authentication is used"""
544 return self._internal_dict.get(SupportedKeywords.APPLICATION_KEY)
545
546 @property
547 def application_certificate(self) -> Optional[str]:
548 """A PEM encoded certificate private key."""
549 return self._internal_dict.get(SupportedKeywords.APPLICATION_CERTIFICATE_BLOB)
550
551 @application_certificate.setter
552 def application_certificate(self, value: str):
553 self[SupportedKeywords.APPLICATION_CERTIFICATE_BLOB] = value
554
555 @property
556 def application_certificate_thumbprint(self) -> Optional[str]:
557 """hex encoded thumbprint of the certificate."""
558 return self._internal_dict.get(SupportedKeywords.APPLICATION_CERTIFICATE_THUMBPRINT)
559
560 @application_certificate_thumbprint.setter
561 def application_certificate_thumbprint(self, value: str):
562 self[SupportedKeywords.APPLICATION_CERTIFICATE_THUMBPRINT] = value
563
564 @property
565 def authority_id(self) -> Optional[str]:
566 """The ID of the AAD tenant where the application is configured.
567 (should be supplied only for non-Microsoft tenant)"""
568 return self._internal_dict.get(SupportedKeywords.AUTHORITY_ID)
569
570 @authority_id.setter
571 def authority_id(self, value: str):
572 self[SupportedKeywords.AUTHORITY_ID] = value
573
574 @property
575 def aad_federated_security(self) -> Optional[bool]:
576 """A Boolean value that instructs the client to perform AAD federated authentication."""
577 return self._internal_dict.get(SupportedKeywords.FEDERATED_SECURITY)
578
579 @property
580 def user_token(self) -> Optional[str]:
581 """User token."""
582 return self._internal_dict.get(SupportedKeywords.USER_TOKEN)
583
584 @property
585 def application_token(self) -> Optional[str]:
586 """Application token."""
587 return self._internal_dict.get(SupportedKeywords.APPLICATION_TOKEN)
588
589 @property
590 def client_details(self) -> ClientDetails:
591 return ClientDetails(self.application_for_tracing, self.user_name_for_tracing)
592
593 @property
594 def login_hint(self) -> Optional[str]:
595 return self._internal_dict.get(SupportedKeywords.USER_ID)
596
597 @property
598 def domain_hint(self) -> Optional[str]:
599 return self._internal_dict.get(SupportedKeywords.AUTHORITY_ID)
600
601 @property
602 def password(self) -> Optional[str]:
603 return self._internal_dict.get(SupportedKeywords.PASSWORD)
604
605 def _set_connector_details(
606 self,
607 name: str,
608 version: str,
609 app_name: Optional[str] = None,
610 app_version: Optional[str] = None,
611 send_user: bool = False,
612 override_user: Optional[str] = None,
613 additional_fields: Optional[List[Tuple[str, str]]] = None,
614 ):
615 """
616 Sets the connector details for tracing purposes.
617 :param name: The name of the connector
618 :param version: The version of the connector
619 :param send_user: Whether to send the user name
620 :param override_user: Override the user name ( if send_user is True )
621 :param app_name: The name of the containing application
622 :param app_version: The version of the containing application
623 :param additional_fields: Additional fields to add to the header
624 """
625 client_details = ClientDetails.set_connector_details(name, version, app_name, app_version, send_user, override_user, additional_fields)
626
627 self.application_for_tracing = client_details.application_for_tracing
628 self.user_name_for_tracing = client_details.user_name_for_tracing
629
630 def __str__(self) -> str:
631 dict_copy = self._internal_dict.copy()
632 for key in dict_copy:
633 if Keyword.lookup(key).secret:
634 dict_copy[key] = "****"
635 return self._build_connection_string(dict_copy)
636
637 def __repr__(self) -> str:
638 return self._build_connection_string(self._internal_dict)
639
640 def _build_connection_string(self, kcsb_as_dict: dict) -> str:
641 return ";".join(["{0}={1}".format(word.value, kcsb_as_dict[word]) for word in SupportedKeywords if word in kcsb_as_dict])
642
643 def _parse_data_source(self, url: str):
644 url = urlparse(url)
645 if not url.netloc:
646 return
647 segments = url.path.lstrip("/").split("/")
648 if len(segments) == 1 and segments[0] and not self.initial_catalog:
649 self.initial_catalog = segments[0]
650 self._internal_dict[SupportedKeywords.DATA_SOURCE] = url._replace(path="").geturl()