|
6 | 6 |
|
7 | 7 | from databricks.sql.types import SSLOptions |
8 | 8 | from databricks.sql.auth.auth import get_python_sql_connector_auth_provider |
9 | | -from databricks.sql.auth.auth_utils import decode_token, is_same_host |
10 | 9 | from databricks.sql.auth.authenticators import AccessTokenAuthProvider |
11 | 10 | from databricks.sql.auth.common import ClientContext |
12 | | -from databricks.sql.common.url_utils import normalize_host_with_protocol |
13 | 11 | from databricks.sql.exc import SessionAlreadyClosedError, DatabaseError, RequestError |
14 | 12 | from databricks.sql import __version__ |
15 | 13 | from databricks.sql import USER_AGENT_NAME |
@@ -50,167 +48,24 @@ def __getattr__(name: str) -> Any: |
50 | 48 | raise AttributeError(f"module {__name__!r} has no attribute {name!r}") |
51 | 49 |
|
52 | 50 |
|
53 | | -_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m") |
54 | | - |
55 | | - |
56 | | -def _redact(value: str) -> str: |
57 | | - """Keep only scheme and host[:port] of a URI or host string for an error message. |
58 | | -
|
59 | | - Userinfo, path, query and fragment can carry credentials, so they never reach an |
60 | | - exception text or log line. |
61 | | - """ |
62 | | - scheme, sep, rest = value.partition("://") |
63 | | - if not sep: |
64 | | - scheme, rest = "", value |
65 | | - elif scheme.lower() not in ("http", "https"): |
66 | | - # Not a real scheme: in a scheme-less URI such as "h.io/x?token=t&next=https://e", |
67 | | - # everything before "://" is path and query, so none of it is shown. |
68 | | - scheme = "<redacted>" |
69 | | - # A "/" or "?" can sit inside a password, and "@" can sit in a path, so once any |
70 | | - # userinfo marker is present the whole authority is dropped rather than guessed at. |
71 | | - if "@" in value or "%40" in value.lower(): |
72 | | - return f"{scheme}{sep}<redacted>" |
73 | | - try: |
74 | | - host = urlsplit(f"//{rest}").netloc |
75 | | - except ValueError: |
76 | | - # urlsplit refuses some hosts (bad IPv6, NFKC-unsafe text); show none of them. |
77 | | - return f"{scheme}{sep}<redacted>" |
78 | | - return f"{scheme}{sep}{host}" |
79 | | - |
80 | | - |
81 | | -def _uri_host_and_path(uri: str) -> Tuple[str, str]: |
82 | | - """Split a ``_connection_uri`` into the kernel host (scheme, authority) and path.""" |
83 | | - try: |
84 | | - parts = urlsplit(uri) |
85 | | - except ValueError: |
86 | | - parts = None |
87 | | - if parts is None: |
88 | | - # Raised outside the except block so no chained exception carries urlsplit's netloc. |
89 | | - raise ValueError( |
90 | | - f"Invalid _connection_uri {_redact(uri)!r}: could not be parsed" |
91 | | - ) |
92 | | - try: |
93 | | - port = parts.port |
94 | | - except ValueError: |
95 | | - port = 0 |
96 | | - if ( |
97 | | - parts.scheme not in ("http", "https") |
98 | | - or not parts.hostname |
99 | | - or "@" in parts.netloc |
100 | | - or port == 0 |
101 | | - # urlsplit reads "h.io:" as no port; an empty port is malformed. |
102 | | - or parts.netloc.endswith(":") |
103 | | - or parts.path in ("", "/") |
104 | | - ): |
105 | | - raise ValueError( |
106 | | - f"Invalid _connection_uri {_redact(uri)!r}: expected http(s)://host[:port]/path with a " |
107 | | - "warehouse path and no credentials" |
108 | | - ) |
109 | | - return f"{parts.scheme}://{parts.netloc}", parts.path + ( |
110 | | - f"?{parts.query}" if parts.query else "" |
111 | | - ) |
112 | | - |
113 | | - |
114 | 51 | def _kernel_endpoint( |
115 | 52 | server_hostname: str, http_path: str, kwargs: dict |
116 | 53 | ) -> Tuple[str, str, Any]: |
117 | 54 | """Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host |
118 | | - (with any port in it) and the path, and wins over ``_port``, so no port is passed. |
119 | | - Otherwise ``server_hostname``, ``http_path`` and ``_port`` pass through as is: the |
120 | | - kernel validates the port and applies it to the host. |
| 55 | + (with any port in it) and the path, and wins over ``_port``. Otherwise the arguments |
| 56 | + pass through as is; the kernel validates the port and applies it to the host. |
121 | 57 | """ |
122 | | - if kwargs.get("_connection_uri"): |
123 | | - host, path = _uri_host_and_path(kwargs["_connection_uri"]) |
124 | | - return host, path, None |
125 | | - return server_hostname, http_path, kwargs.get("_port") |
126 | | - |
127 | | - |
128 | | -def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool: |
129 | | - """True when ``access_token`` is a JWT whose issuer is not ``server_hostname``. Thrift |
130 | | - token-exchanges such a token at server_hostname (TokenFederationProvider); the kernel |
131 | | - wraps every provider with the connection host, so it exchanges at the connection host. |
132 | | - """ |
133 | | - claims = decode_token(access_token) |
134 | | - if not claims: |
135 | | - return False |
136 | | - issuer = claims.get("iss", "") |
137 | | - return not is_same_host(issuer, normalize_host_with_protocol(server_hostname)) |
138 | | - |
139 | | - |
140 | | -def _server_origin(server_hostname: str) -> Tuple[str, Optional[int]]: |
141 | | - """Host and port of ``server_hostname`` for the OAuth origin check. A value with no |
142 | | - comparable origin (credentials, a bare IPv6 literal, an empty or out-of-range port) |
143 | | - returns ``("", None)``, so it never matches and is reported as an origin mismatch. |
144 | | - """ |
145 | | - netloc = server_hostname.rstrip("/").rpartition("://")[2] |
146 | | - # urlsplit reads a trailing ':' as an empty port, which has no origin. |
147 | | - if netloc.endswith(":"): |
148 | | - return "", None |
149 | | - try: |
150 | | - parts = urlsplit(f"//{netloc}") |
151 | | - port = parts.port |
152 | | - except ValueError: |
153 | | - return "", None |
154 | | - if port == 0 or ("@" in parts.netloc and parts.password is not None): |
155 | | - return "", None |
156 | | - return parts.hostname or "", port |
157 | | - |
158 | | - |
159 | | -def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None: |
160 | | - """AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``. |
161 | | - Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls. |
162 | | - URI-only use (empty server_hostname) has no server origin to compare and is not checked. |
163 | | - """ |
164 | | - if not (kwargs.get("_connection_uri") and server_hostname): |
165 | | - return |
166 | | - access_token = kwargs.get("access_token") |
167 | | - # A JWT from a foreign issuer is exchanged, so it is an OAuth credential even though |
168 | | - # it arrives as access_token. Thrift judges the issuer against server_hostname and the |
169 | | - # kernel against its connection host, so a token foreign to either is exchanged. |
170 | | - foreign_jwt = bool( |
171 | | - access_token |
172 | | - and ( |
173 | | - _is_foreign_jwt(access_token, server_hostname) |
174 | | - or _is_foreign_jwt(access_token, kernel_host) |
175 | | - ) |
176 | | - ) |
177 | | - # identity_federation_client_id makes the kernel exchange the access_token at the |
178 | | - # connection host (mandatory workload-identity exchange), so it is exchanged like a |
179 | | - # foreign JWT, whatever the token's issuer. |
180 | | - federated = bool(access_token and kwargs.get("identity_federation_client_id")) |
181 | | - exchanged = foreign_jwt or federated |
182 | | - oauth = ( |
183 | | - kwargs.get("auth_type") in _OAUTH_AUTH_TYPES |
184 | | - or kwargs.get("oauth_jwt_key_file") |
185 | | - or (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret")) |
186 | | - or exchanged |
187 | | - ) |
188 | | - # The kernel auth bridge routes an access_token with no JWT or client-secret |
189 | | - # M2M credentials to PAT, even for auth_type='databricks-oauth'; azure-sp-m2m |
190 | | - # is resolved before that branch and stays OAuth. A custom credentials_provider |
191 | | - # is rejected by the bridge, so it is not an OAuth origin here. |
192 | | - routed_to_pat = ( |
193 | | - bool(access_token) |
194 | | - and not exchanged |
195 | | - and kwargs.get("auth_type") != "azure-sp-m2m" |
196 | | - and not kwargs.get("oauth_jwt_key_file") |
197 | | - and not (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret")) |
198 | | - ) |
199 | | - if routed_to_pat or not oauth: |
200 | | - return |
201 | | - server_host, port = _server_origin(server_hostname) |
202 | | - uri = urlsplit(kernel_host) |
203 | | - if (uri.scheme, uri.hostname or "", uri.port or 443) != ( |
204 | | - "https", |
205 | | - server_host, |
206 | | - port or 443, |
207 | | - ): |
| 58 | + uri = kwargs.get("_connection_uri") |
| 59 | + if not uri: |
| 60 | + return server_hostname, http_path, kwargs.get("_port") |
| 61 | + parts = urlsplit(uri) |
| 62 | + # Credentials in the URI would reach the transport, so they are refused here. |
| 63 | + if parts.scheme not in ("http", "https") or not parts.netloc or "@" in parts.netloc: |
208 | 64 | raise ValueError( |
209 | | - f"OAuth requires the _connection_uri origin to match " |
210 | | - f"https://{_redact(server_hostname)}; " |
211 | | - f"the kernel would send the credentials to {_redact(kernel_host)}. " |
212 | | - "Use a PAT or match the origin." |
| 65 | + "Invalid _connection_uri: expected http(s)://host[:port]/path with no credentials" |
213 | 66 | ) |
| 67 | + path = parts.path + (f"?{parts.query}" if parts.query else "") |
| 68 | + return f"{parts.scheme}://{parts.netloc}", path, None |
214 | 69 |
|
215 | 70 |
|
216 | 71 | class Session: |
@@ -492,7 +347,6 @@ def _create_backend( |
492 | 347 | kernel_host, kernel_http_path, kernel_port = _kernel_endpoint( |
493 | 348 | server_hostname, http_path, kwargs |
494 | 349 | ) |
495 | | - _check_oauth_origin(server_hostname, kernel_host, kwargs) |
496 | 350 | if kernel_http_path != http_path: |
497 | 351 | # A _connection_uri can point at another workspace: re-derive the |
498 | 352 | # SPOG org-id header from the resolved path (a caller header still wins). |
|
0 commit comments