Skip to content

Commit 01999fa

Browse files
cathleenyIsaac
andcommitted
fix(kernel): guard a JWT that is foreign to the _connection_uri host
The OAuth origin guard judged a JWT's issuer only against server_hostname. The kernel judges it against its connection host, so a token issued by server_hostname with a _connection_uri on another host was treated as a PAT here but exchanged by the kernel at that other host. A token foreign to either host now counts as exchanged, so the mismatched origin is rejected. Added the h.io issuer + other.io URI case. Tests: - The loopback realkernel tests skip when the installed wheel has no port kwarg, and re-raise NotSupportedError instead of swallowing it and timing out. They pass on a wheel built from the kernel PR and skip on the published 1.4.0 wheel. - The old-wheel port test uses a fixed-signature fake Session, so the real signature introspection decides, as in the geospatial test. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 6272ae0 commit 01999fa

3 files changed

Lines changed: 73 additions & 26 deletions

File tree

‎src/databricks/sql/session.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,15 @@ def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) ->
183183
return
184184
access_token = kwargs.get("access_token")
185185
# A JWT from a foreign issuer is exchanged, so it is an OAuth credential even though
186-
# it arrives as access_token.
187-
foreign_jwt = bool(access_token and _is_foreign_jwt(access_token, server_hostname))
186+
# it arrives as access_token. Thrift judges the issuer against server_hostname and the
187+
# kernel against its connection host, so a token foreign to either is exchanged.
188+
foreign_jwt = bool(
189+
access_token
190+
and (
191+
_is_foreign_jwt(access_token, server_hostname)
192+
or _is_foreign_jwt(access_token, kernel_host)
193+
)
194+
)
188195
# identity_federation_client_id makes the kernel exchange the access_token at the
189196
# connection host (mandatory workload-identity exchange), so it is exchanged like a
190197
# foreign JWT, whatever the token's issuer.

‎tests/unit/test_kernel_client.py‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -595,12 +595,29 @@ def test_port_kwargs_are_empty_without_a_port():
595595

596596
def test_port_requires_kernel_wheel_that_accepts_port(monkeypatch):
597597
"""A wheel whose fixed ``Session`` signature has no ``port`` raises instead of
598-
connecting to the default port."""
599-
fake_session = MagicMock()
600-
monkeypatch.setattr(
601-
kernel_client, "_kernel_session_accepts_kwarg", lambda name: name != "port"
602-
)
603-
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
598+
connecting to the default port. The real signature introspection decides."""
599+
calls = []
600+
601+
def fake_session_without_port(
602+
host,
603+
http_path,
604+
*,
605+
catalog=None,
606+
schema=None,
607+
session_conf=None,
608+
complex_types_as_json=False,
609+
intervals_as_string=False,
610+
request_timeout_secs=None,
611+
auth_type=None,
612+
access_token=None,
613+
enable_geospatial_support=False,
614+
):
615+
calls.append(host)
616+
sess = MagicMock()
617+
sess.session_id = "sess-id"
618+
return sess
619+
620+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session_without_port)
604621
c = kernel_client.KernelDatabricksClient(
605622
server_hostname="example.cloud.databricks.com",
606623
http_path="/sql/1.0/warehouses/abc",
@@ -609,9 +626,9 @@ def test_port_requires_kernel_wheel_that_accepts_port(monkeypatch):
609626
port=8443,
610627
)
611628

612-
with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"):
629+
with pytest.raises(NotSupportedError, match="_port requires a newer"):
613630
c.open_session(session_configuration=None, catalog=None, schema=None)
614-
fake_session.assert_not_called()
631+
assert calls == []
615632

616633

617634
def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch):

‎tests/unit/test_session.py‎

Lines changed: 39 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from databricks.sql.exc import (
2323
ReydenThriftUnsupportedError,
2424
DatabaseError,
25+
NotSupportedError,
2526
OperationalError,
2627
)
2728
from databricks.sql.session import Session
@@ -1446,6 +1447,9 @@ def _jwt(issuer):
14461447
),
14471448
# An issuer on the server host is not exchanged (Thrift parity), so it passes.
14481449
("h.io", "https://h.io/sql/x", _jwt("https://h.io/oidc"), False),
1450+
# The same issuer is foreign to a different _connection_uri host, where the kernel
1451+
# exchanges it, so the mismatched origin fails.
1452+
("h.io", "https://other.io/sql/x", _jwt("https://h.io/oidc"), True),
14491453
# A PAT is not a JWT and is not guarded.
14501454
("h.io", "https://evil.io/sql/x", "dapi-xyz", False),
14511455
],
@@ -1652,27 +1656,45 @@ def test_spog_org_id_follows_resolved_path(fake_kernel, hp, uri, expected_org):
16521656
)
16531657

16541658

1659+
def _require_real_kernel_wheel(port_kwarg):
1660+
"""Skip unless the kernel wheel is installed and, when ``port_kwarg`` is set, its
1661+
``Session`` takes ``port``. An older wheel raises NotSupportedError for a non-default
1662+
``_port``, which a loopback test would otherwise report as a listener timeout."""
1663+
try:
1664+
ilm.version("databricks-sql-kernel")
1665+
except ilm.PackageNotFoundError:
1666+
pytest.skip("databricks-sql-kernel wheel not installed")
1667+
if port_kwarg:
1668+
from databricks.sql.backend.kernel import client as kernel_client
1669+
1670+
if not kernel_client._kernel_session_accepts_kwarg("port"):
1671+
pytest.skip("installed databricks-sql-kernel wheel has no port kwarg")
1672+
1673+
16551674
@pytest.mark.realkernel
16561675
@pytest.mark.parametrize(
1657-
"build",
1676+
"build, port_kwarg",
16581677
[
1659-
lambda p: {"server_hostname": "127.0.0.1", "http_path": _P, "_port": p},
1660-
lambda p: {
1661-
"server_hostname": "",
1662-
"http_path": "",
1663-
"_connection_uri": f"https://127.0.0.1:{p}{_P}",
1664-
},
1678+
(
1679+
lambda p: {"server_hostname": "127.0.0.1", "http_path": _P, "_port": p},
1680+
True,
1681+
),
1682+
(
1683+
lambda p: {
1684+
"server_hostname": "",
1685+
"http_path": "",
1686+
"_connection_uri": f"https://127.0.0.1:{p}{_P}",
1687+
},
1688+
False,
1689+
),
16651690
],
16661691
ids=["port", "uri-only"],
16671692
)
1668-
def test_kernel_dials_over_tls(build):
1693+
def test_kernel_dials_over_tls(build, port_kwarg):
16691694
"""Loopback dial on the real kernel wheel: a TCP listener on 127.0.0.1 must receive the
16701695
kernel's TLS handshake (first byte 0x16) at the requested port. Nothing completes the
16711696
handshake, so connect() is expected to fail; only the dial is asserted."""
1672-
try:
1673-
ilm.version("databricks-sql-kernel")
1674-
except ilm.PackageNotFoundError:
1675-
pytest.skip("databricks-sql-kernel wheel not installed")
1697+
_require_real_kernel_wheel(port_kwarg)
16761698
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
16771699
listener.bind(("127.0.0.1", 0))
16781700
listener.listen(1)
@@ -1701,6 +1723,8 @@ def accept_one():
17011723
_retry_stop_after_attempts_count=1,
17021724
**build(port),
17031725
).close()
1726+
except NotSupportedError:
1727+
raise
17041728
except Exception:
17051729
pass # expected: nothing behind the listener completes TLS
17061730
thread.join(timeout=70)
@@ -1712,10 +1736,7 @@ def accept_one():
17121736
def test_kernel_embedded_port_wins_over_explicit_port():
17131737
"""Loopback on the real kernel wheel: server_hostname 'h:P1' with an explicit _port P2
17141738
dials P1 (TLS first byte 0x16) and never P2."""
1715-
try:
1716-
ilm.version("databricks-sql-kernel")
1717-
except ilm.PackageNotFoundError:
1718-
pytest.skip("databricks-sql-kernel wheel not installed")
1739+
_require_real_kernel_wheel(port_kwarg=True)
17191740

17201741
def listen():
17211742
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -1756,6 +1777,8 @@ def accept_one(name, sock):
17561777
_retry_stop_after_attempts_count=1,
17571778
_port=explicit_port,
17581779
).close()
1780+
except NotSupportedError:
1781+
raise
17591782
except Exception:
17601783
pass # expected: nothing behind the listener completes TLS
17611784
for thread in threads:

0 commit comments

Comments
 (0)