Skip to content

Commit 189dcf3

Browse files
starheljschoedl
andauthored
Add support for HTTP header for Trino (#1774)
* feat(trino): add support for http headers * Treat Trino JWT tokens and HTTP headers as secrets in the API guard `datacontract api` now answers 422 when DATACONTRACT_TRINO_JWT_TOKEN or DATACONTRACT_TRINO_HTTP_HEADERS is set in the server's environment and the posted contract picks the host, unless DATACONTRACT_TRINO_HOST pins it. Before, only DATACONTRACT_TRINO_PASSWORD was protected this way. * Drop Trino header tests that repeat existing coverage --------- Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent c66554a commit 189dcf3

9 files changed

Lines changed: 80 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
## [Unreleased]
9+
### Added
10+
- Trino connections support custom HTTP headers via `DATACONTRACT_TRINO_HTTP_HEADERS`
911

1012
### Fixed
1113
- Inlining a linked definition merges `logicalTypeOptions` key by key, and allowed values the contract declares in an older form (`logicalTypeOptions.enum`, the `enum` custom property, the `invalidValues` quality rule) win over the definition's `enum`

‎datacontract/api.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ def _parse_filters_query(filters: str | None) -> dict[str, str] | None:
525525
"mysql": ("host", "mysql_host", ("mysql_password",)),
526526
"oracle": ("host", "oracle_host", ("oracle_password",)),
527527
"impala": ("host", "impala_host", ("impala_password",)),
528-
"trino": ("host", "trino_host", ("trino_password",)),
528+
"trino": ("host", "trino_host", ("trino_password", "trino_jwt_token", "trino_http_headers")),
529529
"exasol": ("host", "exasol_host", ("exasol_password",)),
530530
"clickhouse": ("host", "clickhouse_host", ("clickhouse_password",)),
531531
"hive": ("host", "hive_host", ("hive_password",)),

‎datacontract/config/settings.py‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import json
56
import logging
67
import os
78
from pathlib import Path
@@ -338,6 +339,7 @@ class Config(BaseSettings):
338339
trino_username: str | None = None
339340
trino_password: SecretStr | None = None
340341
trino_jwt_token: SecretStr | None = None
342+
trino_http_headers: SecretStr | None = None
341343
# overrides for the contract's servers block
342344
trino_host: str | None = None
343345
trino_port: int | None = None
@@ -506,6 +508,29 @@ def _bool_option(self, field_name: str, default: bool) -> bool:
506508
# A set-but-empty variable counts as false, matching pre-Config parsing.
507509
return str(value).strip().lower() in _TRUTHY
508510

511+
def _dict_option(self, field_name: str, required: bool = False) -> dict[str, str] | None:
512+
"""Parse JSON-object or comma-separated ``key=value`` connection properties."""
513+
text = self._str_option(field_name, required)
514+
if not text:
515+
return None
516+
if text.startswith("{"):
517+
try:
518+
parsed = json.loads(text)
519+
except json.JSONDecodeError as e:
520+
key = env_name(field_name, type(self).model_fields[field_name])
521+
server_type = field_name.split("_")[0]
522+
from datacontract.model.exceptions import DataContractException
523+
524+
raise DataContractException(
525+
type=f"{server_type}-connection",
526+
name=f"invalid_mapping_{key}",
527+
reason=f"{key} is not valid JSON: {e}",
528+
engine="datacontract-cli",
529+
)
530+
return {str(k): str(v) for k, v in parsed.items()}
531+
pairs = (pair.partition("=") for pair in text.split(",") if pair.strip())
532+
return {key.strip(): value.strip() for key, _, value in pairs if key.strip()}
533+
509534
# --- entropy ---
510535
def get_entropy_data_api_key(self, required: bool = False) -> str | None:
511536
return self._str_option("entropy_data_api_key", required)
@@ -706,8 +731,8 @@ def get_iceberg_s3_endpoint(self, required: bool = False) -> str | None:
706731
def get_iceberg_signing_name(self, required: bool = False) -> str | None:
707732
return self._str_option("iceberg_signing_name", required)
708733

709-
def get_iceberg_properties(self, required: bool = False) -> str | None:
710-
return self._str_option("iceberg_properties", required)
734+
def get_iceberg_properties(self, required: bool = False) -> dict[str, str] | None:
735+
return self._dict_option("iceberg_properties", required)
711736

712737
def get_iceberg_credential(self, required: bool = False) -> str | None:
713738
return self._str_option("iceberg_credential", required)
@@ -1056,6 +1081,9 @@ def get_trino_password(self, required: bool = False) -> str | None:
10561081
def get_trino_jwt_token(self, required: bool = False) -> str | None:
10571082
return self._str_option("trino_jwt_token", required)
10581083

1084+
def get_trino_http_headers(self, required: bool = False) -> dict[str, str] | None:
1085+
return self._dict_option("trino_http_headers", required)
1086+
10591087
def get_trino_host(self, required: bool = False) -> str | None:
10601088
return self._str_option("trino_host", required)
10611089

‎datacontract/engines/ibis/connections/connect.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,9 @@ def _connect_trino(ibis, server: Server, config: Config):
882882
database=config.get_trino_catalog() or server.catalog,
883883
schema=config.get_trino_schema() or server.schema_,
884884
)
885+
http_headers = config.get_trino_http_headers()
886+
if http_headers is not None:
887+
kwargs["http_headers"] = http_headers
885888

886889
if authentication == "basic":
887890
user = config.get_trino_username(required=True)

‎datacontract/engines/ibis/connections/iceberg.py‎

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
from __future__ import annotations
1010

11-
import json
1211
import re
1312
from typing import TYPE_CHECKING, Optional
1413

@@ -83,7 +82,7 @@ def catalog_properties(server: Server, config: Config | None = None) -> dict[str
8382
properties["rest.signing-region"] = region
8483
extra = config.get_iceberg_properties()
8584
if extra:
86-
properties.update(_parse_properties(extra))
85+
properties.update(extra)
8786
return properties
8887

8988

@@ -102,24 +101,6 @@ def aws_region(catalog_url: str) -> Optional[str]:
102101
return match.group("region") if match else None
103102

104103

105-
def _parse_properties(text: str) -> dict[str, str]:
106-
"""Extra pyiceberg catalog properties: a JSON object, or ``key=value`` pairs separated by commas."""
107-
text = text.strip()
108-
if text.startswith("{"):
109-
try:
110-
parsed = json.loads(text)
111-
except json.JSONDecodeError as e:
112-
raise DataContractException(
113-
type="iceberg-connection",
114-
name="invalid_properties",
115-
reason=f"DATACONTRACT_ICEBERG_PROPERTIES is not valid JSON: {e}",
116-
engine="datacontract-cli",
117-
)
118-
return {str(k): str(v) for k, v in parsed.items()}
119-
pairs = (pair.partition("=") for pair in text.split(",") if pair.strip())
120-
return {key.strip(): value.strip() for key, _, value in pairs if key.strip()}
121-
122-
123104
def load_iceberg_catalog(server: Server, config: Config | None = None) -> Catalog:
124105
"""Open the server's REST catalog with pyiceberg."""
125106
try:

‎docs/docs/configuration.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,7 @@ Every option, by its environment variable name and the matching `Config` field.
416416
| `DATACONTRACT_TRINO_USERNAME` | `trino_username` | string | |
417417
| `DATACONTRACT_TRINO_PASSWORD` | `trino_password` | string (secret) | |
418418
| `DATACONTRACT_TRINO_JWT_TOKEN` | `trino_jwt_token` | string (secret) | |
419+
| `DATACONTRACT_TRINO_HTTP_HEADERS` | `trino_http_headers` | string (secret) | |
419420
| `DATACONTRACT_TRINO_HOST` | `trino_host` | string | Overrides `host` from the contract's `servers` block |
420421
| `DATACONTRACT_TRINO_PORT` | `trino_port` | integer | Overrides `port` from the contract's `servers` block |
421422
| `DATACONTRACT_TRINO_CATALOG` | `trino_catalog` | string | Overrides `catalog` from the contract's `servers` block |

‎docs/docs/reference/trino.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@ servers:
3232

3333
`host`, `port`, `catalog`, and `schema` come from the contract's `servers` block, and can be overridden with `DATACONTRACT_TRINO_HOST`, `DATACONTRACT_TRINO_PORT`, `DATACONTRACT_TRINO_CATALOG`, and `DATACONTRACT_TRINO_SCHEMA`.
3434

35+
## Custom HTTP headers
36+
37+
Set `DATACONTRACT_TRINO_HTTP_HEADERS` to a JSON object or comma-separated `key=value` pairs:
38+
39+
```bash
40+
export DATACONTRACT_TRINO_HTTP_HEADERS='{"X-Trino-Client-Info":"datacontract-cli","X-Trino-Routing-Group":"analytics"}'
41+
```
42+
43+
Headers are passed to `trino.dbapi.connect(http_headers=...)` for both `datacontract test` and `datacontract import trino`. The JSON or `key=value` string is stored as a secret and masked in `Config` representations.
44+
3545
## Data types
3646

3747
### Importing

‎tests/test_api.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -891,6 +891,22 @@ def test_guard_allows_caller_supplied_credentials(monkeypatch):
891891
_reject_environment_credentials_to_untrusted_host(_POSTGRES_CONTRACT, "production", config) # no raise
892892

893893

894+
@pytest.mark.parametrize("secret", ["DATACONTRACT_TRINO_JWT_TOKEN", "DATACONTRACT_TRINO_HTTP_HEADERS"])
895+
def test_guard_blocks_env_trino_secrets(monkeypatch, secret):
896+
monkeypatch.setenv(secret, "prod-secret")
897+
monkeypatch.delenv("DATACONTRACT_TRINO_HOST", raising=False)
898+
from fastapi import HTTPException
899+
900+
with pytest.raises(HTTPException) as exc:
901+
_reject_environment_credentials_to_untrusted_host(
902+
_POSTGRES_CONTRACT.replace("type: postgres", "type: trino").replace("database:", "catalog:"),
903+
"production",
904+
None,
905+
)
906+
assert exc.value.status_code == 422
907+
assert secret in exc.value.detail
908+
909+
894910
def test_test_endpoint_blocks_credential_exfiltration(monkeypatch):
895911
"""End to end through the API: POST a contract naming the host while the
896912
server holds a postgres password -> 422, no connection attempted."""

‎tests/test_connect_trino.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"DATACONTRACT_TRINO_USERNAME",
1818
"DATACONTRACT_TRINO_PASSWORD",
1919
"DATACONTRACT_TRINO_JWT_TOKEN",
20+
"DATACONTRACT_TRINO_HTTP_HEADERS",
2021
"DATACONTRACT_TRINO_HOST",
2122
"DATACONTRACT_TRINO_PORT",
2223
"DATACONTRACT_TRINO_CATALOG",
@@ -140,3 +141,18 @@ def test_env_variables_override_the_contract_server_details(env, captured_connec
140141
assert captured_connect["port"] == 8443
141142
assert captured_connect["database"] == "env_catalog"
142143
assert captured_connect["schema"] == "env_schema"
144+
145+
146+
def test_http_headers_are_forwarded(env, captured_connect):
147+
env.setenv("DATACONTRACT_TRINO_USERNAME", "my_user")
148+
env.setenv(
149+
"DATACONTRACT_TRINO_HTTP_HEADERS",
150+
'{"X-Trino-Client-Info": "datacontract-cli", "X-Trino-Routing-Group": "analytics"}',
151+
)
152+
153+
_connect()
154+
155+
assert captured_connect["http_headers"] == {
156+
"X-Trino-Client-Info": "datacontract-cli",
157+
"X-Trino-Routing-Group": "analytics",
158+
}

0 commit comments

Comments
 (0)