Skip to content

Commit 8f96c0b

Browse files
cathleenyIsaac
andcommitted
fix(kernel): keep credentials and resolved host details out of error messages
Error messages that echoed a _connection_uri, server_hostname or the OAuth origin now show only scheme and host[:port] through a redaction helper, so userinfo, path, query and fragment never reach exception text or logs. Adds regression tests that the secret does not appear in the message, and a mocked connect() test that the resolved kernel host and path reach KernelDatabricksClient. Removes a duplicate import in the unit test module. No validation semantics change. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com>
1 parent 6a78cef commit 8f96c0b

2 files changed

Lines changed: 74 additions & 8 deletions

File tree

‎src/databricks/sql/session.py‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,19 @@ def _port_or_none(value: Any) -> Optional[int]:
6868
return int(text) or None
6969

7070

71+
def _redact(value: str) -> str:
72+
"""Keep only scheme and host[:port] of a URI or host string for an error message.
73+
74+
Userinfo, path, query and fragment can carry credentials, so they never reach an
75+
exception text or log line.
76+
"""
77+
scheme, sep, rest = value.partition("://")
78+
if not sep:
79+
scheme, rest = "", value
80+
host = rest.split("/", 1)[0].rpartition("@")[2]
81+
return f"{scheme}{sep}{re.split(r'[?#]', host, maxsplit=1)[0]}"
82+
83+
7184
def _split_host(host: str) -> Tuple[str, str, Optional[int]]:
7285
"""Split ``[scheme://]name[:port]`` into ``(prefix, name, port)``; ``name`` keeps IPv6 brackets."""
7386
prefix, sep, text = host.rstrip("/").rpartition("://")
@@ -76,15 +89,15 @@ def _split_host(host: str) -> Tuple[str, str, Optional[int]]:
7689
if match is None:
7790
if text.startswith("[") or text.count(":") == 1:
7891
raise ValueError(
79-
f"Invalid server_hostname {host!r}: malformed IPv6 literal or port"
92+
f"Invalid server_hostname {_redact(host)!r}: malformed IPv6 literal or port"
8093
)
8194
return prefix, text, None # an unbracketed IPv6 literal such as ::1 has no port
8295
name, port_text = match.group(1), match.group(2)
8396
if port_text is None:
8497
return prefix, name, None
8598
if not 1 <= int(port_text) <= 65535:
8699
raise ValueError(
87-
f"Invalid server_hostname {host!r}: port {port_text} is out of range"
100+
f"Invalid server_hostname {_redact(host)!r}: port {port_text} is out of range"
88101
)
89102
return prefix, name, int(port_text)
90103

@@ -104,7 +117,7 @@ def _uri_host_and_path(uri: str) -> Tuple[str, str]:
104117
or parts.path in ("", "/")
105118
):
106119
raise ValueError(
107-
f"Invalid _connection_uri {uri!r}: expected http(s)://host[:port]/path with a "
120+
f"Invalid _connection_uri {_redact(uri)!r}: expected http(s)://host[:port]/path with a "
108121
"warehouse path and no credentials"
109122
)
110123
return f"{parts.scheme}://{parts.netloc}", parts.path + (
@@ -132,7 +145,7 @@ def _kernel_host_and_path(
132145
if embedded is not None:
133146
if embedded != port:
134147
raise ValueError(
135-
f"Conflicting ports: server_hostname {server_hostname!r} carries {embedded} but _port={port}"
148+
f"Conflicting ports: server_hostname {_redact(server_hostname)!r} carries {embedded} but _port={port}"
136149
)
137150
return server_hostname, http_path
138151
if port == 443:
@@ -174,8 +187,8 @@ def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) ->
174187
port or 443,
175188
):
176189
raise ValueError(
177-
f"OAuth requires the _connection_uri origin to match https://{server_hostname}; "
178-
f"the kernel would send the credentials to {kernel_host}. Use a PAT or match the origin."
190+
f"OAuth requires the _connection_uri origin to match https://{_redact(server_hostname)}; "
191+
f"the kernel would send the credentials to {_redact(kernel_host)}. Use a PAT or match the origin."
179192
)
180193

181194

‎tests/unit/test_session.py‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,6 @@
2525
)
2626
from databricks.sql.session import Session
2727

28-
import databricks.sql
29-
3028

3129
class TestSession:
3230
"""
@@ -1387,6 +1385,61 @@ def test_oauth_origin_guard(server, kwargs, uri, should_raise):
13871385
_check_oauth_origin(server, kernel_host, kwargs)
13881386

13891387

1388+
@pytest.mark.parametrize(
1389+
"uri, secret",
1390+
[
1391+
("https://user:secret@h.io/sql/x", "secret"),
1392+
("https://h.io:8443?token=secret", "secret"),
1393+
],
1394+
)
1395+
def test_invalid_connection_uri_message_omits_credentials(uri, secret):
1396+
with pytest.raises(ValueError, match="Invalid _connection_uri") as exc:
1397+
_kernel_host_and_path("h", _P, {"_connection_uri": uri})
1398+
assert secret not in str(exc.value)
1399+
1400+
1401+
def test_oauth_origin_message_omits_uri_query():
1402+
kwargs = {
1403+
"auth_type": "databricks-oauth",
1404+
"_connection_uri": "https://evil.io/sql/x?token=secret",
1405+
}
1406+
kernel_host = _kernel_host_and_path("h.io", _P, kwargs)[0]
1407+
with pytest.raises(ValueError, match="requires the _connection_uri origin") as exc:
1408+
_check_oauth_origin("h.io", kernel_host, kwargs)
1409+
assert "secret" not in str(exc.value)
1410+
assert "https://evil.io" in str(exc.value)
1411+
1412+
1413+
@pytest.mark.parametrize(
1414+
"conn_kwargs, expected_host, expected_path",
1415+
[
1416+
({"server_hostname": "h.io", "http_path": _P, "_port": 8443}, "h.io:8443", _P),
1417+
(
1418+
{
1419+
"server_hostname": "",
1420+
"http_path": "",
1421+
"_connection_uri": f"https://d.io:9999{_P}",
1422+
},
1423+
"https://d.io:9999",
1424+
_P,
1425+
),
1426+
],
1427+
)
1428+
def test_resolved_kernel_host_and_path_reach_kernel_client(
1429+
fake_kernel, conn_kwargs, expected_host, expected_path
1430+
):
1431+
client, _ = fake_kernel
1432+
databricks.sql.connect(
1433+
use_kernel=True,
1434+
access_token="dapi-xyz",
1435+
enable_telemetry=False,
1436+
**conn_kwargs,
1437+
)
1438+
kwargs = client.call_args.kwargs
1439+
assert kwargs["server_hostname"] == expected_host
1440+
assert kwargs["http_path"] == expected_path
1441+
1442+
13901443
@pytest.fixture
13911444
def fake_kernel():
13921445
"""Fake the kernel wheel and client so connect() runs without a warehouse."""

0 commit comments

Comments
 (0)