Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions sqlit/domains/connections/providers/mssql/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@
# Entra access token instead of having the driver acquire one itself.
SQL_COPT_SS_ACCESS_TOKEN = 1256

# Hosts whose self-signed certificate is trusted without asking: a local SQL
# Server or Docker container, where there is no network path to intercept.
_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", ".", "(local)", "(localdb)"})


def is_local_host(host: str) -> bool:
"""Return True for a host on this machine, ignoring any instance name."""
base = host.strip().split("\\")[0].split(",")[0].lower()
return base in _LOCAL_HOSTS or base.startswith("(localdb)")


def _build_access_token_struct(token: str) -> bytes:
"""Pack a JWT into the layout SQL_COPT_SS_ACCESS_TOKEN expects.
Expand Down Expand Up @@ -252,14 +262,19 @@ def _build_connection_string(self, config: ConnectionConfig, *, attach_token: bo
base = f"SERVER={server_with_port};" f"DATABASE={endpoint.database or 'master'};"

tls_mode = get_tls_mode(config)
trust_value = str(config.get_option("tls_trust_server_certificate", "yes")).lower()
trust_server_cert = "no" if trust_value in {"no", "false", "0"} else "yes"

security_parts: list[str] = []
if tls_mode != TLS_MODE_DEFAULT:
if tls_mode == TLS_MODE_DEFAULT:
# The trust option is hidden in this mode, so a stored value is the
# old form default rather than a choice. Verify the certificate
# (the driver's default) unless the server is on this machine.
if is_local_host(endpoint.host):
security_parts.append("TrustServerCertificate=yes;")
else:
trust_value = str(config.get_option("tls_trust_server_certificate", "yes")).lower()
trust_server_cert = "no" if trust_value in {"no", "false", "0"} else "yes"
encrypt_value = "no" if tls_mode == TLS_MODE_DISABLE else "yes"
security_parts.append(f"Encrypt={encrypt_value};")
security_parts.append(f"TrustServerCertificate={trust_server_cert};")
security_parts.append(f"TrustServerCertificate={trust_server_cert};")

base = base + "".join(security_parts)

Expand Down
70 changes: 70 additions & 0 deletions sqlit/domains/connections/ui/connection_error_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,79 @@ def on_result(added: bool) -> None:
)


_UNTRUSTED_CERT_MARKERS = (
"certificate verify failed",
"certificate chain was issued by an authority that is not trusted",
)


def is_untrusted_certificate_error(message: str) -> bool:
text = message.lower()
return any(marker in text for marker in _UNTRUSTED_CERT_MARKERS)


@dataclass(frozen=True)
class UntrustedServerCertificateHandler:
"""Offer to trust a SQL Server certificate that cannot be verified.

SQL Server verifies the server certificate by default. A server with a
self-signed certificate then fails to connect; ask once, and remember the
answer on the connection, the way SSH asks about an unknown host key.
"""

def can_handle(self, error: Exception) -> bool:
return is_untrusted_certificate_error(str(error))

def handle(self, app: ConnectionErrorApp, error: Exception, config: ConnectionConfig) -> None:
from sqlit.shared.ui.screens.confirm import ConfirmScreen
from sqlit.shared.ui.screens.error import ErrorScreen

if config.db_type != "mssql":
app.push_screen(ErrorScreen("Connection Failed", str(error)))
return

endpoint = config.tcp_endpoint
host = endpoint.host if endpoint else "The server"

def on_result(confirmed: bool | None) -> None:
if not confirmed:
return
trust_server_certificate(app, config)
app.connect_to_server(config)

app.push_screen(
ConfirmScreen(
"Untrusted server certificate",
f"{host} presented a certificate that can't be verified, "
"usually because it is self-signed.\n\n"
"Trust it for this connection? Only do this for a server you know: "
"on an untrusted network, someone could be impersonating it.",
yes_label="Trust this server",
no_label="Cancel",
),
on_result,
)


def trust_server_certificate(app: ConnectionErrorApp, config: ConnectionConfig) -> None:
"""Encrypt without verifying the certificate, and save that on the connection."""
from sqlit.domains.connections.providers.tls import TLS_MODE_REQUIRE

config.set_option("tls_mode", TLS_MODE_REQUIRE)
config.set_option("tls_trust_server_certificate", "yes")
if not config.name or all(c.name != config.name for c in app.connections):
return
app.connections = [config if c.name == config.name else c for c in app.connections]
try:
app.services.connection_store.save_one(config)
except Exception as exc:
app.notify(f"Trusted for this session, but could not save: {exc}", severity="warning")


_DEFAULT_HANDLERS: tuple[ConnectionErrorHandler, ...] = (
AzureFirewallHandler(),
MissingDriverHandler(),
UntrustedServerCertificateHandler(),
)


Expand Down
39 changes: 39 additions & 0 deletions tests/unit/test_tls_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,42 @@ def test_mssql_tls_flags_in_connection_string():
conn_str = adapter.build_connection_string(config)
assert "Encrypt=yes;" in conn_str
assert "TrustServerCertificate=no;" in conn_str


def _mssql_config(server: str, **options: str) -> ConnectionConfig:
return ConnectionConfig(
name="mssql",
db_type="mssql",
server=server,
port="1433",
database="master",
username="sa",
password="secret",
options={"auth_type": "sql", **options},
)


def test_mssql_default_tls_verifies_remote_certificates():
"""Default TLS mode must not blindly trust a remote server's certificate.

Saved connections carry the old hidden form default ("yes"); in default mode
it is not a choice the user made, so it must not switch verification off.
"""
import pytest

from sqlit.domains.connections.providers.mssql.adapter import SQLServerAdapter

adapter = SQLServerAdapter()
cases = [
("myserver.database.windows.net", {}, False),
("myserver.database.windows.net", {"tls_trust_server_certificate": "yes"}, False),
("10.0.0.5", {"tls_mode": "default", "tls_trust_server_certificate": "yes"}, False),
("localhost", {}, True),
("127.0.0.1", {}, True),
(".\\SQLEXPRESS", {}, True),
("db.internal", {"tls_mode": "require", "tls_trust_server_certificate": "yes"}, True),
]
for server, options, trusted in cases:
conn_str = adapter.build_connection_string(_mssql_config(server, **options))
if ("TrustServerCertificate=yes;" in conn_str) != trusted:
pytest.fail(f"{server} {options}: expected trusted={trusted}, got {conn_str!r}")
80 changes: 80 additions & 0 deletions tests/unit/test_untrusted_certificate_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""Trusting an unverifiable SQL Server certificate from the connection error."""

from __future__ import annotations

from typing import Any

from sqlit.domains.connections.ui.connection_error_handlers import handle_connection_error
from tests.helpers import ConnectionConfig

ODBC_SELF_SIGNED = (
"[Microsoft][ODBC Driver 18 for SQL Server]SSL Provider: "
"[error:0A000086:SSL routines::certificate verify failed:self-signed certificate]"
)


class _Store:
def __init__(self) -> None:
self.saved: list[Any] = []

def save_one(self, config: Any, previous_name: str | None = None) -> None:
self.saved.append(config)


class _Services:
def __init__(self) -> None:
self.connection_store = _Store()


class _App:
def __init__(self, connections: list[Any]) -> None:
self.services = _Services()
self.connections = connections
self.screens: list[tuple[Any, Any]] = []
self.connected: list[Any] = []

def push_screen(self, screen: Any, callback: Any = None) -> None:
self.screens.append((screen, callback))

def connect_to_server(self, config: Any) -> None:
self.connected.append(config)

def notify(self, *args: Any, **kwargs: Any) -> None:
pass


def _config() -> ConnectionConfig:
return ConnectionConfig(
name="prod", db_type="mssql", server="sql.corp.local", port="1433",
database="master", username="sa", password="secret", options={"auth_type": "sql"},
)


def test_confirming_trusts_saves_and_reconnects():
config = _config()
app = _App([config])

assert handle_connection_error(app, RuntimeError(ODBC_SELF_SIGNED), config)
screen, callback = app.screens[-1]
assert type(screen).__name__ == "ConfirmScreen"

callback(True)

from sqlit.domains.connections.providers.mssql.adapter import SQLServerAdapter

conn_str = SQLServerAdapter().build_connection_string(config)
assert "Encrypt=yes;TrustServerCertificate=yes;" in conn_str
assert app.services.connection_store.saved == [config]
assert app.connected == [config]


def test_declining_changes_nothing():
config = _config()
app = _App([config])

handle_connection_error(app, RuntimeError(ODBC_SELF_SIGNED), config)
app.screens[-1][1](False)

assert config.get_option("tls_mode") is None
assert app.services.connection_store.saved == []
assert app.connected == []
Loading