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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,30 @@ conn = connect(
)
```

### Authentication over insecure transport

By default, the client refuses to send authentication credentials (for example `BasicAuthentication`) over an
unencrypted `http://` connection, raising a `TrinoAuthError`. This is intentional as it avoids credentials being sent
in plaintext.

If the connection is already encrypted below the application layer (for example the client only ever talks to a
Trino coordinator through an mTLS-terminating service mesh sidecar on `localhost`), this check gets in the way even
though the underlying transport is secure. In that case, set `allow_insecure_auth` to `True` to opt out of the
check. Depending on the coordinator's configuration, you may additionally need to set
`http-server.authentication.allow-insecure-over-http=true` on the coordinator.

```python
from trino.dbapi import connect
from trino.auth import BasicAuthentication

conn = connect(
user="<username>",
auth=BasicAuthentication("<username>", "<password>"),
http_scheme="http",
allow_insecure_auth=True
)
```

## Spooled protocol

The client spooling protocol requires [a Trino server with spooling protocol support](https://trino.io/docs/current/client/client-protocol.html#spooling-protocol).
Expand Down
47 changes: 47 additions & 0 deletions tests/unit/sqlalchemy/test_dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from sqlalchemy.engine.url import make_url
from sqlalchemy.engine.url import URL

import trino.exceptions
from trino.auth import BasicAuthentication
from trino.auth import OAuth2Authentication
from trino.dbapi import Connection
Expand Down Expand Up @@ -222,6 +223,27 @@ def setup_method(self):
legacy_prepared_statements=False,
),
),
(
make_url(trino_url(
user="user",
password="pass",
host="localhost",
allow_insecure_auth=True,
)),
'trino://user:***@localhost:8080/'
'?allow_insecure_auth=true'
'&source=trino-sqlalchemy',
list(),
dict(
host="localhost",
port=8080,
catalog="system",
user="user",
auth=BasicAuthentication("user", "pass"),
source="trino-sqlalchemy",
allow_insecure_auth=True,
),
),
],
)
def test_create_connect_args(
Expand All @@ -248,6 +270,31 @@ def test_create_connect_args_wrong_db_format(self):
with pytest.raises(ValueError, match="Unexpected database format catalog/schema/foobar"):
self.dialect.create_connect_args(url)

def test_create_connect_args_allow_insecure_auth_permits_connection_over_http(self):
# Default port (8080) resolves to http_scheme="http" in Connection; without
# allow_insecure_auth this would raise TrinoAuthError.
url = make_url(trino_url(user="user", password="pass", host="localhost", allow_insecure_auth=True))
args, kwargs = self.dialect.create_connect_args(url)
assert kwargs["allow_insecure_auth"] is True

Connection(*args, **kwargs)

def test_create_connect_args_allow_insecure_auth_false_raises_over_http(self):
url = make_url(trino_url(user="user", password="pass", host="localhost", allow_insecure_auth=False))
args, kwargs = self.dialect.create_connect_args(url)
assert kwargs["allow_insecure_auth"] is False

with pytest.raises(trino.exceptions.TrinoAuthError, match="TLS/SSL is required for authentication"):
Connection(*args, **kwargs)

def test_create_connect_args_without_allow_insecure_auth_raises_over_http(self):
url = make_url(trino_url(user="user", password="pass", host="localhost"))
args, kwargs = self.dialect.create_connect_args(url)
assert "allow_insecure_auth" not in kwargs

with pytest.raises(trino.exceptions.TrinoAuthError, match="TLS/SSL is required for authentication"):
Connection(*args, **kwargs)

def test_get_default_isolation_level(self):
isolation_level = self.dialect.get_default_isolation_level(mock.Mock())
assert isolation_level == "AUTOCOMMIT"
Expand Down
20 changes: 20 additions & 0 deletions tests/unit/test_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,26 @@ def test_no_error_when_auth_over_https():
Connection("mytrinoserver.domain", http_scheme=constants.HTTPS, auth=BasicAuthentication("u", "p"))


def test_error_when_auth_over_http_mentions_allow_insecure_auth():
with pytest.raises(trino.exceptions.TrinoAuthError, match="allow_insecure_auth=True"):
Connection("mytrinoserver.domain", http_scheme=constants.HTTP, auth=BasicAuthentication("u", "p"))


def test_no_error_when_auth_over_http_with_allow_insecure_auth():
connection = Connection(
"mytrinoserver.domain",
http_scheme=constants.HTTP,
auth=BasicAuthentication("u", "p"),
allow_insecure_auth=True,
)
assert connection.http_scheme == constants.HTTP
# Ensure the flag doesn't just suppress the constructor check, but also
# doesn't prevent building a request object that would actually be used
# to send the (insecure) authenticated requests.
request = connection._create_request()
assert request._http_scheme == constants.HTTP


def _statement_uri(query_id, token):
return f"{SERVER_ADDRESS}{constants.URL_STATEMENT_PATH}/{query_id}/{token}"

Expand Down
9 changes: 7 additions & 2 deletions trino/dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def __init__(
timezone=None,
encoding: Union[str, List[str]] = _USE_DEFAULT_ENCODING,
heartbeat_interval: Optional[float] = constants.DEFAULT_HEARTBEAT_INTERVAL,
allow_insecure_auth: bool = False,
):
# Automatically assign http_schema, port based on hostname
parsed_host = urlparse(host, allow_fragments=False)
Expand Down Expand Up @@ -217,11 +218,15 @@ def __init__(
else:
self.http_scheme = constants.HTTP

if auth is not None and self.http_scheme == constants.HTTP:
if auth is not None and self.http_scheme == constants.HTTP and not allow_insecure_auth:
raise trino.exceptions.TrinoAuthError(
"TLS/SSL is required for authentication. "
"To use HTTPS, specify 'https://' in the host URL (which takes precedence "
"over http_scheme), or, if the host URL has no scheme, pass http_scheme='https'."
"over http_scheme), or, if the host URL has no scheme, pass http_scheme='https'. "
"If your connection is encrypted below the application layer (for example behind an mTLS "
"service mesh sidecar), pass allow_insecure_auth=True and ensure "
"http-server.authentication.allow-insecure-over-http=true is set on the coordinator if it "
"has HTTPS enabled."
)

# Infer connection port: `hostname` takes precedence over explicit `port` argument
Expand Down
3 changes: 3 additions & 0 deletions trino/sqlalchemy/dialect.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ def create_connect_args(self, url: URL) -> Tuple[Sequence[Any], Mapping[str, Any
if "verify" in url.query:
kwargs["verify"] = json.loads(url.query["verify"])

if "allow_insecure_auth" in url.query:
kwargs["allow_insecure_auth"] = json.loads(url.query["allow_insecure_auth"])

if "roles" in url.query:
kwargs["roles"] = json.loads(url.query["roles"])

Expand Down
6 changes: 5 additions & 1 deletion trino/sqlalchemy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ def _url(
cert: Optional[str] = None,
key: Optional[str] = None,
verify: Optional[bool] = None,
roles: Optional[Dict[str, str]] = None
roles: Optional[Dict[str, str]] = None,
allow_insecure_auth: Optional[bool] = None,
) -> str:
"""
Composes a SQLAlchemy connection string from the given database connection
Expand Down Expand Up @@ -134,4 +135,7 @@ def _url(
if roles is not None:
trino_url += f"&roles={quote_plus(json.dumps(roles))}"

if allow_insecure_auth is not None:
trino_url += f"&allow_insecure_auth={json.dumps(allow_insecure_auth)}"

return trino_url
Loading