|
1 | 1 | import logging |
2 | 2 | import re |
3 | 3 | from functools import cached_property |
| 4 | +from urllib.parse import urlsplit |
4 | 5 | from typing import Dict, Tuple, List, Optional, Any, Type, TYPE_CHECKING |
5 | 6 |
|
6 | 7 | from databricks.sql.types import SSLOptions |
@@ -47,6 +48,126 @@ def __getattr__(name: str) -> Any: |
47 | 48 | raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |
48 | 49 |
|
49 | 50 |
|
| 51 | +_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m") |
| 52 | +_HOSTPORT_RE = re.compile(r"(\[[^\]]*\]|(?!\[)[^:]*)(?::([0-9]+))?") |
| 53 | + |
| 54 | + |
| 55 | +def _port_or_none(value: Any) -> Optional[int]: |
| 56 | + """Validate ``_port``. ``None`` and ``0`` mean the default (Thrift: ``port or 443``).""" |
| 57 | + if value is None: |
| 58 | + return None |
| 59 | + text = ( |
| 60 | + str(value).strip() |
| 61 | + if isinstance(value, (int, str)) and not isinstance(value, bool) |
| 62 | + else "" |
| 63 | + ) |
| 64 | + if not re.fullmatch(r"[0-9]+", text) or not int(text) <= 65535: |
| 65 | + raise ValueError( |
| 66 | + f"Invalid _port {value!r}: expected an integer between 1 and 65535" |
| 67 | + ) |
| 68 | + return int(text) or None |
| 69 | + |
| 70 | + |
| 71 | +def _split_host(host: str) -> Tuple[str, str, Optional[int]]: |
| 72 | + """Split ``[scheme://]name[:port]`` into ``(prefix, name, port)``; ``name`` keeps IPv6 brackets.""" |
| 73 | + prefix, sep, text = host.rstrip("/").rpartition("://") |
| 74 | + prefix += sep |
| 75 | + match = _HOSTPORT_RE.fullmatch(text) |
| 76 | + if match is None: |
| 77 | + if text.startswith("[") or text.count(":") == 1: |
| 78 | + raise ValueError( |
| 79 | + f"Invalid server_hostname {host!r}: malformed IPv6 literal or port" |
| 80 | + ) |
| 81 | + return prefix, text, None # an unbracketed IPv6 literal such as ::1 has no port |
| 82 | + name, port_text = match.group(1), match.group(2) |
| 83 | + if port_text is None: |
| 84 | + return prefix, name, None |
| 85 | + if not 1 <= int(port_text) <= 65535: |
| 86 | + raise ValueError( |
| 87 | + f"Invalid server_hostname {host!r}: port {port_text} is out of range" |
| 88 | + ) |
| 89 | + return prefix, name, int(port_text) |
| 90 | + |
| 91 | + |
| 92 | +def _uri_host_and_path(uri: str) -> Tuple[str, str]: |
| 93 | + """Split a ``_connection_uri`` into the kernel host (scheme and authority) and path (with query).""" |
| 94 | + parts = urlsplit(uri) |
| 95 | + try: |
| 96 | + port = parts.port |
| 97 | + except ValueError: |
| 98 | + port = 0 |
| 99 | + if ( |
| 100 | + parts.scheme not in ("http", "https") |
| 101 | + or not parts.hostname |
| 102 | + or "@" in parts.netloc |
| 103 | + or port == 0 |
| 104 | + or parts.path in ("", "/") |
| 105 | + ): |
| 106 | + raise ValueError( |
| 107 | + f"Invalid _connection_uri {uri!r}: expected http(s)://host[:port]/path with a " |
| 108 | + "warehouse path and no credentials" |
| 109 | + ) |
| 110 | + return f"{parts.scheme}://{parts.netloc}", parts.path + ( |
| 111 | + f"?{parts.query}" if parts.query else "" |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +def _kernel_host_and_path( |
| 116 | + server_hostname: str, http_path: Optional[str], kwargs: dict |
| 117 | +) -> Tuple[str, Optional[str]]: |
| 118 | + """Resolve the kernel ``(host, http_path)``. ``_connection_uri`` replaces both and wins over |
| 119 | + ``_port``; ``_port`` folds into the host as ``host:port`` (default 443 adds nothing). |
| 120 | + """ |
| 121 | + if kwargs.get("_connection_uri"): |
| 122 | + return _uri_host_and_path(kwargs["_connection_uri"]) |
| 123 | + port = _port_or_none(kwargs.get("_port")) |
| 124 | + prefix, name, embedded = _split_host(server_hostname) |
| 125 | + if port is None: |
| 126 | + return server_hostname, http_path |
| 127 | + if not server_hostname: |
| 128 | + raise ValueError( |
| 129 | + "server_hostname is required on use_kernel=True when _port is set " |
| 130 | + "(or pass _connection_uri, which carries its own host)" |
| 131 | + ) |
| 132 | + if embedded is not None: |
| 133 | + if embedded != port: |
| 134 | + raise ValueError( |
| 135 | + f"Conflicting ports: server_hostname {server_hostname!r} carries {embedded} but _port={port}" |
| 136 | + ) |
| 137 | + return server_hostname, http_path |
| 138 | + if port == 443: |
| 139 | + return server_hostname, http_path |
| 140 | + if ":" in name and not name.startswith("["): |
| 141 | + name = f"[{name}]" |
| 142 | + return f"{prefix}{name}:{port}", http_path |
| 143 | + |
| 144 | + |
| 145 | +def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None: |
| 146 | + """AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``. |
| 147 | + Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls. |
| 148 | + URI-only use (empty server_hostname) has no server origin to compare and is not checked. |
| 149 | + """ |
| 150 | + oauth = ( |
| 151 | + kwargs.get("auth_type") in _OAUTH_AUTH_TYPES |
| 152 | + or kwargs.get("oauth_jwt_key_file") |
| 153 | + or (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret")) |
| 154 | + or kwargs.get("credentials_provider") is not None |
| 155 | + ) |
| 156 | + if not (kwargs.get("_connection_uri") and server_hostname and oauth): |
| 157 | + return |
| 158 | + _, name, port = _split_host(server_hostname) |
| 159 | + uri = urlsplit(kernel_host) |
| 160 | + if (uri.scheme, uri.hostname or "", uri.port or 443) != ( |
| 161 | + "https", |
| 162 | + name.strip("[]").lower(), |
| 163 | + port or 443, |
| 164 | + ): |
| 165 | + raise ValueError( |
| 166 | + f"OAuth requires the _connection_uri origin to match https://{server_hostname}; " |
| 167 | + f"the kernel would send the credentials to {kernel_host}. Use a PAT or match the origin." |
| 168 | + ) |
| 169 | + |
| 170 | + |
50 | 171 | class Session: |
51 | 172 | def __init__( |
52 | 173 | self, |
@@ -323,9 +444,23 @@ def _create_backend( |
323 | 444 | "_telemetry_circuit_breaker_enabled" |
324 | 445 | ), |
325 | 446 | } |
| 447 | + kernel_host, kernel_http_path = _kernel_host_and_path( |
| 448 | + server_hostname, http_path, kwargs |
| 449 | + ) |
| 450 | + _check_oauth_origin(server_hostname, kernel_host, kwargs) |
| 451 | + if kernel_http_path != http_path: |
| 452 | + # A _connection_uri can point at another workspace: re-derive the |
| 453 | + # SPOG org-id header from the resolved path (a caller header still wins). |
| 454 | + base_headers = [ |
| 455 | + h for h in all_headers if h not in self._spog_headers.items() |
| 456 | + ] |
| 457 | + self._spog_headers = self._extract_spog_headers( |
| 458 | + kernel_http_path, base_headers |
| 459 | + ) |
| 460 | + all_headers = base_headers + list(self._spog_headers.items()) |
326 | 461 | return KernelDatabricksClient( |
327 | | - server_hostname=server_hostname, |
328 | | - http_path=http_path, |
| 462 | + server_hostname=kernel_host, |
| 463 | + http_path=kernel_http_path, |
329 | 464 | http_headers=all_headers, |
330 | 465 | auth_provider=auth_provider, |
331 | 466 | ssl_options=self.ssl_options, |
|
0 commit comments